2
我想解耦一个实现,其中的接口是知道的,实现将在App.Config中定义。但它似乎无法解析界面。使用Autofac与XML配置
这是我在做什么:
<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配置解析时的界面?
谢谢,这工作! –