DI autofac& mvc 6 beta7

时间:2015-10-03 10:37:29

标签: c# asp.net autofac

我遇到了Autofac解决方案的问题。我不能用mvc 6 beta7。

使用依赖:

  "Autofac": "4.0.0-beta7-130",
  "Microsoft.AspNet.Mvc": "6.0.0-beta7",

我的Startup.cs

 public IContainer Container { get; set; }
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // Create the autofac container
        var builder = new ContainerBuilder();
        // Create the container and use the default application services as a fallback
        //AutofacRegistration.Populate(builder, services);

        // Add any Autofac modules or registrations.
        builder.RegisterModule(new AutofacModule());

        Container = builder.Build();

    }

    public void Configure(IApplicationBuilder app)
    {
        //app.Run(async (context) =>
        //{
        //    await context.Response.WriteAsync("Hello World!");
        //});
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });

        app.ApplicationServices = Container.Resolve<IServiceProvider>();
    }

采取此例外

  

Autofac.dll中出现“Autofac.Core.Registration.ComponentNotRegisteredException”类型的异常,但未在用户代码中处理

     

其他信息:请求的服务“System.IServiceProvider”尚未注册。要避免此异常,请注册组件以提供服务,使用IsRegistered()检查服务注册,或使用ResolveOptional()方法解析可选依赖项。

如何在MVC 6 beta 7中使用autofac?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容替换ConfigureServices方法,以使autofac正常工作。

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   // Add MVC services to the services container.
   services.AddMvc();

   // Create the autofac container
   var builder = new ContainerBuilder();
   // Create the container and use the default application services as a fallback
   //AutofacRegistration.Populate(builder, services);

   // Populate the services.
   builder.Populate(services);

   // Add any Autofac modules or registrations.
   builder.RegisterModule(new AutofacModule());

   Container = builder.Build();

   // Resolve and return the service provider.
   return Container.Resolve<IServiceProvider>();
}
相关问题