Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
856 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - Ninject Scope issue with Tasks/Threads

I have an MVC3 project that uses Ninject, Entity Framework and the Unit of Work pattern with a Service layer.

My AsyncService class has a function that starts a background task that, as an example, adds users to the User repository. My current problem is that the task only runs correctly for a few seconds before I get an error that the DbContext has been disposed. My database context, which is injected with Ninject's InRequestScope() seems to be getting disposed, as InRequestScope() ties it to HttpContext.

I've read about InThreadScope(), however I'm not sure how to implement it properly in my MVC project.

My Question is: What is the correct way to use Ninject in my Task?

public class AsyncService
{
    private CancellationTokenSource cancellationTokenSource;
    private IUnitOfWork _uow;
    public AsyncService(IUnitOfWork uow)
    {
        _uow = uow;
    }
    public void AsyncStartActivity(Activity activity)
    {
    ...snip...
        this.cancellationTokenSource = new CancellationTokenSource();
        var cancellationToken = this.cancellationTokenSource.Token;
        var task = Task.Factory.StartNew(() =>
            {
                foreach (var user in activity.UserList)
                {
                    this._uow.UserRepository.Add(new User() {UserID = user});
                }
                this._uow.Save();
            }, cancellationToken);
     ...snip...
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

InRequestScope'd objects are Disposed at the end of a request so it can't be used in this case. InThreadScope also doesn't fit as that would reuse the UoW for several tasks.

What you can do though is declare your AsyncService as the Scoping Object for all the objects within using the NamedScope extension.

See http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...