简体   繁体   中英

How to use Simple Injector to inject a class into my custom model binder provider?

I'm trying to build a simple blog website in MVC Core.

Currently, I have aa custom model binder provider which looks something like this (where IBlogRepository is my database repository using nHibernate):

public class PostModelBinderProvider : IModelBinderProvider
{
    IBlogRepository _blogRepository;
    public PostModelBinderProvider(IBlogRepository blogRepository)
    {
        _blogRepository = blogRepository;
    }


    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        //code
    }
}

And it is registered like this:

services.AddMvc(config => config.ModelBinderProviders.Insert(0, new PostModelBinderProvider(container.GetInstance<IBlogRepository>())));

But then I get this exception when attempting to run the application: SimpleInjector.ActivationException: 'The ISession is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.'

Currently, my front end makes an ajax call which sends the blog-post data (title, content and tags) to the server. The tags are represented by an integer which corresponds to their unique IDs in the database. The Model binder is doing a lookup on the database of the tag, and then saving the post.

So I have a look online, and there seems to be a divided opinion about whether I should be touching the database at all in the model binder.

Question:

  • So, assuming that it's okay to get data from the database in the model binder, how do I make Simple Injector work with it?

  • Alternatively, if it's not okay to get data from the database in the model binder, where would I put the logic for this?

Your PostModelBinderProvider is effectively a singleton, while the IBlogRepository is transient or scoped. Easiest solution is to change the IBlogRepository dependency to Func <IBlogRepository> instead and change the configuration to the following:

services.AddMvc(config => config.ModelBinderProviders.Insert(0, 
    new PostModelBinderProvider(
          container.GetInstance<IBlogRepository>)));

Inside the PostModelBinderProvider you can now invoke the delegate to get the repository.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM