2

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?

binks
  • 1,001
  • 2
  • 10
  • 26

1 Answers1

2

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.

Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
  • Awesome, I didnt realise I could still put dependancies in the constructors - this makes everything so much easier! – binks Dec 23 '14 at 13:40
  • Hi @Vsevolod, is this thread safe? Im wondering if multiple people call an async function in BookService, would they get their own context? – dalcam Oct 01 '20 at 02:00
  • @dalcam hard to say (I haven't been working with c# for a while), but it depends on the Lifetime of object registered in the IoC – Vsevolod Goloviznin Oct 01 '20 at 07:47