Search code examples
c#entity-frameworkninjectninject-extensions

Configure Ninject Factory to return the same instance every time


I have a service layer that I am reusing (AKA Business Layer).

Here's an example of one of my services with an IMyContextFactory dependency, this returns an instance of IMyContext.

public class MyService : IMyService 
{
    private IMyContextFactory DbContextFactory;

    public MyService(IMyContextFactory dbContextFactory)
    {
        this.DbContextFactory = dbContextFactory;
    }

    public DoSomething(int id)
    {
        // Get instance of the db for use
        IMyContext dbContext = this.DbContextFactory.CreateMyDbContext();

        // Use the business layer for something
        var user = dbContext.Set<User>().Find(id);
    }
}

I am using the Ninject Factory extension.

Is it possible to make the IMyContextFactory to return the same instance of IMyContext every time?

Background

Originally I was injecting IMyDbContext straight into the service without the factory and I had this InRequestScope() when initialized by my ASP.NET MVC website.

But now I am making use of the service it in a Windows Service too and I don't want my DbContext to become bloated because of frequent looping. I didn't want my service to be newed up for every request either, so that's why I thought a factory within the service would do the trick.

I need the best of InRequestScope() and a new instance every time depending on the configuration. I already have a separate config for ASP.NET and for the Windows Service - it's just how I get a singleton each time from the factory.


Solution

  • I'm not fully proficient with Ninject, but according to this page https://github.com/ninject/Ninject.Extensions.Factory/wiki/Factory-interface it seems that the instance returned by the factory is retrieved from the IResolutionRoot.

    My take would be that you have to register your IMyContext concrete type with a singleton lifetime type.

    (But it seems that it's not that of a good idea to not destroy your context, according to Erik Fukenbusch's comment)