Autofac - 通过xml配置将实例传递给构造函数参数

时间:2014-01-17 14:16:15

标签: xml dependency-injection ioc-container autofac

我有一个实现,它将MemoryCache作为构造函数参数。

我的xml配置:

 <autofac defaultAssembly="Test.Caching">
    <component name="memoryCache"
        type="System.Runtime.Caching.MemoryCache, System.Runtime.Caching">
        <parameters>
           <parameter name="name" value="TestCache"/>
        </parameters>
    </component>

    <component type="My.Caching.TaskCache, Test.Caching" service="Test.Caching.ITaskCache" >
        <parameters>
          <parameter name="cache" value="testCache" />
        </parameters>
    </component>
 </autofac>

我正在使用Autofac.Configuration并通过以下方式注册xml:

builder.RegisterModule(new ConfigurationSettingsReader("autofac", "<configPath>"));

我收到以下错误:

System.Configuration.ConfigurationErrorsException: The type 'System.Runtime.Caching.MemoryCache, System.Runtime.Caching' could not be found. It may re
quire assembly qualification, e.g. "MyType, MyAssembly".
   at Autofac.Configuration.ConfigurationRegistrar.LoadType(String typeName, Assembly defaultAssembly)
   at Autofac.Configuration.ConfigurationRegistrar.RegisterConfiguredComponents(ContainerBuilder builder, SectionHandler configurationSection)
   at Autofac.Configuration.ConfigurationRegistrar.RegisterConfigurationSection(ContainerBuilder builder, SectionHandler configurationSection)
   at Autofac.Configuration.Core.ConfigurationModule.Load(ContainerBuilder builder)
   at Autofac.Module.Configure(IComponentRegistry componentRegistry)
   at Autofac.ContainerBuilder.Build(IComponentRegistry componentRegistry, Boolean excludeDefaultModules)
   at Autofac.ContainerBuilder.Build(ContainerBuildOptions options)

我在项目中引用了System.Runtime.Caching。

1 个答案:

答案 0 :(得分:1)

我认为您需要一个声明界面:

<component name="memoryCache"
type="System.Runtime.Caching.MemoryCache, System.Runtime.Caching"
service="your.interface.IMemoryCache, your.interface"