在.NET Core 2.0中配置Autofac出现问题

8
我开始了我的第一个.NET CORE 2.0项目,它是一个WebAPI。一切都很顺利,直到我遇到配置Autofac的问题。我按照这里描述的说明进行操作。但不幸的是,我在StartUp中遇到了编译错误。显然,ContainerBuilder没有包含Populate()的定义。而且类型AutofacServiceProvider无法找到。我在网上搜索了一段时间,试图找到正确的2.0文档。它们零散并且不总是清晰,不知道源代码是否针对1.0或2.0版本。不幸的是,所有选项都以编译错误告终,因此我决定坚持使用官方文档提供的实现。是否可能Autofac不支持.NET Core 2.0中的这种初始化形式?
FYI:
using Autofac;
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace TEST.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var containerBuilder = new ContainerBuilder();
            containerBuilder.RegisterModule<ServiceModule>();
            containerBuilder.Populate(services);
            var container = containerBuilder.Build();
            return new AutofacServiceProvider(container);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}


<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Model\Recipy.Model.csproj" />
    <ProjectReference Include="..\Service\Recipy.Service.csproj" />  
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Autofac" Version="4.6.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="4.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>
</Project>

为什么您使用Autofac而不是内置的DI框架? - Jonathan Allen
2
因为这些模块,而且我以前也用过它。 :) - Nieksa
Jonathan,如果你要使用NancyFx,你需要使用不同的容器。 - norgie
@norgie,你能否提供有关NancyFx + Core 2.1 + Autofac的更多指针,这会很有帮助。 - kudlatiger
1个回答

19

这个问题的解决方法很简单,Populate方法和AutofacServiceProvider都在你现在没有使用的命名空间中。

你还需要引入"Autofac.Extensions.DependencyInjection"。

这两个问题应该就能解决了。


这有点令人难堪。VSCode没有给出添加参考的建议,所以我排除了它,这很愚蠢。感谢您的洞察力。 :) - Nieksa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接