Reputation: 952
I have Autofac set up to auto-inject dependencies into controller constructors, but now I need to manually resolve a dependency (DBcontext
) in a function, which I can't pass the context as a constructor parameter.
Is it bad practice to set the Container as public static variable and to access it than through Startup.Container.Resolve<DbContext>()
?
Edit:
I just found about this piece of code:
AutofacDependencyResolver.Current.ApplicationContainer.Resolve<MyDbContext>();
Is this the correct way to use it? As it just gets the current Container and then resolves?
Upvotes: 1
Views: 919
Reputation: 1701
It is generally considered bad practice to reference the a static property or method to retrieve the global container or resolve a dependency, because you're coupling your code to Autofac, which might hurt you later when you need to refactor or test the code.
Since you mentioned that it is an attribute filter, which is already coupled to MVC (I presume), you could use DependencyResolver.Current
. To do so you need to set up an AutofacDependencyResolver
in your start-up code.
To reduce coupling, you could also resolve the dependency in the filter's constructor, like so:
class MyFilter: ActionFilterAttribute
{
private readonly DbContext _context;
public MyFilter(): this(null)
{
}
internal MyFilter(DbContext context)
{
_context = context ?? DependencyResolver.Current.GetService<DbContext>();
}
}
That way your method has less coupling and you can easily test the method by using the internal constructor.
UPDATE RegisterFilterProvider
is of course a better solution, because you don't need DependencyResolver.Current
.
Upvotes: 2