我在为此提出标题时遇到了一些麻烦,但请考虑以下代码:
public class SomeClass
{
public SomeClass(IEnumerable<IInterface> contracts)
{
_contracts = contracts;
}
private readonly IEnumerable<IInterface> _contracts;
public TService GetValueInstance<TService>(string name)
where TService : class
{
var contract = _contracts.First(x => x.ToString() == name);
var type = contract.Types[typeof(TService)];
var instance = Activator.CreateInstance(type);
return instance as TService;
}
}
public class InterfaceImplementation : IInterface
{
public Dictionary<Type, Type> Types => new Dictionary<Type, Type>
{
{ typeof(Key), typeof(Value)}
};
public override string ToString()
{
return nameof(InterfaceImplementation);
}
}
public interface IInterface
{
Dictionary<Type, Type> Types { get; }
}
public class Key
{
}
public class Value
{
}
所有人都非常吝啬,专注于Activator.CreateInstance。假设注入了IEnumerable'contract'。
问:我有什么方法可以在Autofac中创建注册,这样我就可以删除Activator.CreateInstance并以某种方式直接返回实例化的类型?
InterfaceImplementation.Types属性需要保留。
谢谢!