我刚刚在我的一个应用程序上配置了这个。有不同的方法,但我喜欢这种方法:
Autofac 和 ASP.NET Web API System.Web.Http.Services.IDependencyResolver 集成
首先,我创建了一个实现System.Web.Http.Services.IDependencyResolver
接口的类。
internal class AutofacWebAPIDependencyResolver : System.Web.Http.Services.IDependencyResolver {
private readonly IContainer _container;
public AutofacWebAPIDependencyResolver(IContainer container) {
_container = container;
}
public object GetService(Type serviceType) {
return _container.IsRegistered(serviceType) ? _container.Resolve(serviceType) : null;
}
public IEnumerable<object> GetServices(Type serviceType) {
Type enumerableServiceType = typeof(IEnumerable<>).MakeGenericType(serviceType);
object instance = _container.Resolve(enumerableServiceType);
return ((IEnumerable)instance).Cast<object>();
}
}
我还有另一个班级持有我的注册:
internal class AutofacWebAPI {
public static void Initialize() {
var builder = new ContainerBuilder();
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
new AutofacWebAPIDependencyResolver(RegisterServices(builder))
);
}
private static IContainer RegisterServices(ContainerBuilder builder) {
builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly).PropertiesAutowired();
builder.RegisterType<WordRepository>().As<IWordRepository>();
builder.RegisterType<MeaningRepository>().As<IMeaningRepository>();
return
builder.Build();
}
}
然后,将其初始化为Application_Start
:
protected void Application_Start() {
//...
AutofacWebAPI.Initialize();
//...
}
我希望这有帮助。