我用过autofac,mvc 4.0.
我已经在我的mvc 4.0应用程序的Application_Start中注册了接口和模块.
我也使用了自动连接的属性,例如
protected void Application_Start()
{
//Other codes...
builder.RegisterType<Service>()
.As<IService>()
.InstancePerLifetimeScope()
.PropertiesAutowired());
builder.RegisterControllers(typeof (MvcApplication).Assembly)
.PropertiesAutowired();
...
}
但是,在启动类中未解析依赖项,并且该对象始终为null.
public class Startup
{
public IService MyService { get; set; }
public void Configuration(IAppBuilder app)
{
MyService.SomeMetod(3, "");
}
}
在上面的代码中,我希望MyService成为一个对象,但不是这样,它总是为null,我做错了请帮忙.
请注意,di在控制器中工作,它不在启动类中工作!
解决方法:
我期待AutoFac像控制器类一样自动解析依赖关系.它使用手动解决方案解决如下:
var myService = (IService)DependencyResolver.Current.GetService(typeof(IService ));