Reputation: 124
I'd like to create separated controller only for userManager and dbcontext. I want to inherit from this controller. I don't want to inject dependencies using constructor because in that way I would have to add constructor also to another controllers. Is another way to do this?
private UserManager<ApplicationUser> _userManager;
private ApplicationDbContext _context;
ApplicationDbContext Context
{
get
{
if(this._context == null)
{
// GET CONTEXT <= HOW TO DO THIS?
}
return this._context;
}
}
UserManager<ApplicationUser> UserManager
{
get
{
if(this._userManager == null)
{
// GET USER MANAGER <= HOW TO DO THIS?
}
return this._userManager;
}
}
Upvotes: 1
Views: 375
Reputation: 93063
If you are completely against using Dependency Injection, you can use the Service Locator pattern, but I would advise against it for the reasons detailed in Service Locator is an Anti-Pattern.
If you still don't want to use Dependency Injection, you can use HttpContext.RequestServices
to access an IServiceProvider
instance and use its GetRequiredService
method to request the types you're after, like this:
ApplicationDbContext Context
{
get
{
if (this._context == null)
{
this._context = HttpContext.RequestServices.GetRequiredService<ApplicationDbContext>();
}
return this._context;
}
}
UserManager<ApplicationUser> UserManager
{
get
{
if (this._userManager == null)
{
this._userManager = HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
}
return this._userManager;
}
}
Upvotes: 2