Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Startup.cs中使用DI解析服务_C#_Asp.net Mvc_Dependency Injection_Autofac - Fatal编程技术网

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

C# 在Startup.cs中使用DI解析服务,c#,asp.net-mvc,dependency-injection,autofac,C#,Asp.net Mvc,Dependency Injection,Autofac,我用过autofac,MVC4.0。 我已经在MVC4.0应用程序的应用程序_Start中注册了接口和模块。 我还使用了自动接线的属性 protected void Application_Start() { //Other codes... builder.RegisterType<Service>() .As<IService>() .InstancePerLifetimeScope()

我用过autofac,MVC4.0。 我已经在MVC4.0应用程序的应用程序_Start中注册了接口和模块。 我还使用了自动接线的属性

protected void Application_Start()
        {
//Other codes...
builder.RegisterType<Service>()
                .As<IService>()
                .InstancePerLifetimeScope()
                .PropertiesAutowired());
      builder.RegisterControllers(typeof (MvcApplication).Assembly)
                    .PropertiesAutowired();
...
}
在上面的代码中,我希望MyService是一个对象,但它不是这样的,它总是空的,我是否做错了什么请帮助


请注意,di在控制器中工作,而不仅仅在启动类中工作

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

 var myService = (IService)DependencyResolver.Current.GetService(typeof(IService ));

为了将依赖项注入到
启动
类中,创建调用类实例的类需要由DI容器创建。如果不是,它将不起作用:)如果调用.GetService或类似的代码,它可能会重复,这通常是一种“做错了”的迹象。您正在将启动类绑定到依赖项注入代码,这应该远离“标准代码”内部。更好的解决方案是注册Startup类以进行依赖项注入,如下所示。国际海事组织。
 var myService = (IService)DependencyResolver.Current.GetService(typeof(IService ));