无法创建控制器,依赖项注入

时间:2018-08-27 09:13:18

标签: c# asp.net-mvc dependency-injection

我有以下启动文件(Startup.cs):

public void Configuration(IAppBuilder app)
{


    AutofacConfig.RegisterIoc();
    HttpConfiguration config = new HttpConfiguration();

    ConfigureOAuth(app); //This must come first before we load the WebApiConfig below.

    WebApiConfig.Register(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseWebApi(config);

}

如您所见,我注册了autofac配置。我的autofac配置代码如下:(AutofacConfig.cs)

 public class AutofacConfig
    {
        public static void RegisterIoc()
        {
            var builder = GetBuilder();
            var container = builder.Build();

            // Set dependency resolver for MVC
            //DependencyResolver.SetResolver(new AutofacWebApiDependencyResolver(container));

            // Set dependency resolver for Web API
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }

        public static ContainerBuilder GetBuilder()
        {
            var builder = new ContainerBuilder();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            //builder.RegisterFilterProvider();


            var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(x => x.FullName.Contains("API")).ToArray();
            builder.RegisterAssemblyTypes(assemblies)
                .AsImplementedInterfaces()
                .InstancePerRequest();

            return builder;
        }
    }

但是当我运行应用程序并尝试访问控制器中的方法时,出现以下错误:

  

尝试创建类型的控制器时发生错误   'DataController'。确保控制器有一个   无参数的公共构造函数。

我尝试调试startup.cs,以查看它是否已执行。

在我以前在Global.asax中注册autofac之前,但是由于我使用OAuth,因此我离开了Global.asax,而是创建了一个Startup文件。我想这和这有关系吗?

我的控制器如下:

private readonly IItemModelService _itemModelService;

public DataController(IItemModelService itemModelService)
{
    this._itemModelService = itemModelService;
}

Stacktrace:

  在

  System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage   请求,HttpControllerDescriptor controllerDescriptor,类型   controllerType)在   System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage   要求)   System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()   在System.Linq.Expressions.Expression.New(Type type)在   System.Web.Http.Internal.TypeActivator.Create [TBase](Type   instanceType)位于   System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage   请求,键入controllerType,Func`1&激活器)   System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage   请求,HttpControllerDescriptor controllerDescriptor,类型   controllerType)

1 个答案:

答案 0 :(得分:1)

我在OWIN上使用Oauth,但我不知道这是对基于owin的应用程序autofac的特殊实现。

我的startup.cs看起来像这样,并且可以正常工作:

public void Configuration(IAppBuilder app)
    {
        var builder = new ContainerBuilder();


        //AutofacConfig.RegisterIoc();
        HttpConfiguration config = new HttpConfiguration();

        builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
        var assemblies = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(x => x.FullName.Contains("API")).ToArray();
        builder.RegisterAssemblyTypes(assemblies)
            .AsImplementedInterfaces()
            .InstancePerRequest();

        var container = builder.Build();
        config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

        ConfigureOAuth(app); //This must come first before we load the WebApiConfig below.

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseAutofacMiddleware(container);
        app.UseAutofacWebApi(config);
        app.UseWebApi(config);

    }

我关注了以下链接:

https://autofaccn.readthedocs.io/en/latest/integration/webapi.html#owin-integration

https://autofaccn.readthedocs.io/en/latest/integration/owin.html