Search code examples
c#asp.net-mvcentity-frameworklight-inject

LightInject a database context in MVC


I'm starting to use LightInject in my MVC application, but I'm a bit confused as to how to implement an instance of a DB Context class.

I know I can just inject it via a constructor... but what's the point of LightInject if I have to do this.

Also, the DB Context class in my application already implements an interface (IdentityDbContext) so it somehow doesnt seem right to create another interface for the repository.

The DB Context class does have this in the constructor:

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

So I can quite easily call:

 _context.Create()

In a constructor - but my understand is, this would go against SOLID principles.

So how does one use LightInject to create an instance of a database context class?


Solution

  • You can register the context and then pass it with constructor injection:

    In you ioc configuration file:

    container.Register<Context, Context>(new PerScopeLifetime());
    

    Some service:

    private readonly Context _context;
    
    public BookService(Context context)
    {
        _context = context;
    }
    

    If you want to use an interface, then register an interface and pass it everywhere you want.