使用具有 XML 配置的 Autofac

using Autofac with XML configuration

我正在尝试解耦接口已知且实现将在 App.Config 中定义的实现。但是好像不能解析接口。

这就是我正在做的事情:

<configuration>
  <autofac defaultAssembly="My.Service">    
    <components>
      <component type="My.Services.Service, My.Service" 
                 service="My.Abstractions.IService, My.Service" 
                 instance-scope="per-lifetime-scope" 
                 instance-ownership="lifetime-scope"
                 name="Service"
                 inject-properties="no"/>  
    </components>    
  </autofac>
</configuration>

在我的 C# 代码中

var builder = new ContainerBuilder();
builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
var container = builder.Build();
IService service = container.Resolve<IService>()

当我 运行 代码时,它无法解析我需要的 IService。 如果我做同样的事情,但用代码而不是 xml 实现,这就是它的工作原理。

var builder = new ContainerBuilder();
builder.RegisterType<Service>().As<IService>().InstancePerLifetimeScope();
var container = builder.Build();
IService service = container.Resolve<IService>()

这里是堆栈跟踪

An exception occurred creating the service: IService ---> Autofac.Core.Registration.ComponentNotRegisteredException: 
The requested service 'My.Abstractions.IService' has not been registered. 
To avoid this exception, either register a component to provide the service,
check for service registration using IsRegistered(), 
or use the ResolveOptional() method to resolve an optional dependency.
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve(IComponentContext context, Type serviceType, IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context,IEnumerable`1 parameters)
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context)

谁能解释一下在使用 xml 配置时如何解析接口?

错误来自配置文件中指定的 name 属性。

<component 
      type="My.Services.Service, My.Service" 
      service="My.Abstractions.IService, My.Service" 
      instance-scope="per-lifetime-scope" 
      instance-ownership="lifetime-scope"
      name="Service"
      inject-properties="no"/>  

相当于:

builder.RegisterType<Service>()
       .Named<IService>("Service")
       .InstancePerLifetimeScope();

要得到你想要的,只需要删除name属性,你不需要指定默认值。

<component 
      type="My.Services.Service, My.Service" 
      service="My.Abstractions.IService, My.Service" 
      instance-scope="per-lifetime-scope" />