在 Startup.cs 中使用 DI 解析服务

Thu*_*der 4 c# asp.net-mvc dependency-injection autofac

我使用过 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();
...
}
Run Code Online (Sandbox Code Playgroud)

但是在启动类中没有解析依赖,对象始终为 null 。

 public class Startup
    {
    public IService MyService { get; set; }
        public void Configuration(IAppBuilder app)
        {
            MyService.SomeMetod(3, "");
        }
     }
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我希望 MyService 是一个对象,但它不是,所以它总是为空,我做错了什么请帮助。

请注意 di 是在控制器中工作的,它不仅仅在启动类中工作!

Thu*_*der 5

我期待 AutoFac 像在控制器类中一样自动解决依赖关系,它是使用手动解析解决的,如下所示:

 var myService = (IService)DependencyResolver.Current.GetService(typeof(IService ));
Run Code Online (Sandbox Code Playgroud)