使用带有XML配置的Autofac

时间:2015-05-13 11:52:17

标签: c# xml dependency-injection autofac

我正在尝试解耦接口已知的实现,并且实现将在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>()

这是stacktrace

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配置时如何解析界面吗?

1 个答案:

答案 0 :(得分:3)

错误来自配置文件中指定的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" />