ASP.NET Core Data Access Layer Custom Class AddSingleton

asp.net-core dependency-injection entity-framework-core

Question

I have my EntityFrameworkCore DBContext in ConfigureServices

public void ConfigureServices(IServiceCollection services)
{               
    services.AddDbContext<MyDBContext>(Options => ...  );
    ...
}

I also have my data access layer factory class which receives DBContext in constructor

public partial class DataAccessFactory
{
    public readonly ProductsDataAccess Products;
    public readonly CategoriesDataAccess Categories;

    public DataAccessFactory(MyDBContext db)
    {
        Products = new ProductsDataAccess(db);
        Categories = new CategoriesDataAccess(db);
    }    
}

In order to work with Data Access Layer, I have to create new instance of DataAccessFactory per each request.

My question is, does it make sence and is there any way to create one instance of DataAccessFactory and add it as a Singleton?

1
0
11/20/2018 10:50:49 AM

Accepted Answer

You can register your service inside ConfigureServices in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddSingleton<DataAccessFactory>();
}

and inject it where you needed:

public class MyController
{
    public readonly DataAccessFactory Factory;

    public MyController(DataAccessFactory factory)
    {
        Factory = factory;
    }    
}

It will be created only once per application life. If you instead will want to change it scope for example per request, just change AddSingleton to AddScoped.

Update:

But be careful when mixing different-scoped services. You cannot inject short living object into long living, because it will cause exceptions. In your situation you will need to change DbContext scope to singleton (sic) or consider to change Factory lifetime to Scoped. Here is example how to change DbContext scope.

1
11/20/2018 12:04:39 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow