I see following issues with your approach:
DepdencyResolver
is defined in System.Web.Mvc, and your BL-project should not reference that assembly.
- You are using the Service Locator Pattern, which is declared an Anti-Pattern.
Avoid the System.Web.Mvc-dependency in your BL-project
I found a specific Locator<T>
is a practicable approach, which circumnavigates the "open to everything"- and static-issue of the Service Locator Pattern:
public interface ILocator<T> // defined in some *CORE* project
{
T Locate();
}
public class AutofacLocator<T> : ILocator<T> // defined and injected in your *FRONTEND* project
{
public AutofacLocator(ILifetimeScope lifetimeScope)
{
this.LifetimeScope = lifetimeScope;
}
public virtual T Locate()
{
var service = this.LifetimeScope.Resolve<T>();
return service;
}
}
This can simply be registered as an open generic:
builder.RegisterGeneric(typeof(AutofacLocator<>))
.As(typeof(ILocator<>))
.InstancePerDependency();
So, instead of depending on the static DependencyResolver.Current
, you create your own resolver, and inject it in the BL-class' ctor:
public class SomeBusinessLogic
{
public SomeBusinessLogic(ILocator<SomeDependency> someDependencyLocator)
{
}
}
Use Ctor-Injection instead of the Service Locator Pattern
Another approach would be, to simply define the dependency on a T
-instance as a ctor-parameter, and let Autofac build the instance of your BL-class:
public class SomeBusinessLogic // defined in your *BL* project
{
public SomeBusinessLogic(SomeDependency someDependency)
{
}
}
var someBusinessLogic = DependencyResolver.Current.GetService<SomeBusinessLogic>(); // in your *FRONTEND* project