我有以下类/接口结构:
class ProviderSetting
{
public delegate ProviderSetting Factory(string applicationClientId,
string appKey);
public ProviderSetting (string applicationClientId, string appKey)
{ ... }
}
和
class Provider : IProvider
{
public Provider(ProviderSetting setting)
{ ... }
}
和
class Ingestor: IIngestor
{
public Ingestor (IProvider provider)
{ ... }
}
我使用autofac以下列方式执行依赖注入:
var builder = new ContainerBuilder();
builder.RegisterType<ProviderSetting>().AsSelf();
builder.RegisterGeneratedFactory(typeof(ProviderSetting.Factory));
builder.RegisterType<Provider>().As<IProvider>();
builder.RegisterType<Ingestor>().As<IIngestor>();
并解决如下:
var settings = container.Resolve<ProviderSetting.Factory>().Invoke("<appId>", "<appKey>");
var provider = container.Resolve<IProvider>(new TypedParameter(typeof(ProviderSetting), settings));
var ingestor = container.Resolve<IIngestor>(new TypedParameter(typeof(Provider), provider));
但我得到例外:
DependencyResolutionException:没有使用&#39; Autofac.Core.Activators.Reflection.DefaultConstructorFinder&#39;找到的构造函数。在类型&#39; ProviderSettings&#39;可以使用可用的服务和参数调用: 无法解析参数&SystemString applicationClientId&#39;构造函数&#39; Void .ctor(System.String,System.String)&#39;。
我在这里缺少什么?
答案 0 :(得分:1)
此处发生错误:
var ingestor = container.Resolve<IIngestor>();
这是因为autofac尝试解析Provider
的{{1}},但Ingestor
它尝试解析Provider
无法解决问题。原因是您尚未注册ParameterSettings
的任何参数。代码:
ParameterSettings
仅解析var provider = container.Resolve<IProvider>(new NamedParameter("setting", new ProviderSetting ("<appId>", "<appKey>")));
的实例,并且不会注册上述参数。
要注册这些参数,您需要使用IProvider
扩展名
WithParameters
然后您可以在不明确提供这些参数的情况下解析服务:
builder.RegisterType<ProviderSetting>()
.AsSelf()
.WithParameters(
new[]
{
new NamedParameter("applicationClientId", "someClientId"),
new NamedParameter("appKey", "someAppKey")
});
<强>更新强>: 如果要在解析时提供这些参数,可以为此创建工厂委托:
var provider = container.Resolve<IProvider>();
var ingestor = container.Resolve<IIngestor>();
并注册:
public delegate ProviderSetting ProviderSettingFactory(string applicationClientId, string appKey);
然后你可以像这样解决它:
containerBuilder.RegisterGeneratedFactory(typeof(ProviderSettingFactory));
最后你可以这样做:
var factory = container.Resolve<ProviderSettingFactory>();
ProviderSetting setting = factory("someClientId", "someAppKey");