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配置解析時的界面?
謝謝,這工作! –