【问题标题】:DI autofac & mvc 6 beta7DI autofac & mvc 6 beta7
【发布时间】:2015-10-03 10:37:28
【问题描述】:

我在使用 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?

【问题讨论】:

标签: c# asp.net autofac


【解决方案1】:

您可以将 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>();
}

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2021-06-03
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多