我目前有一个通过反射获取的运行时类型。我需要创建此类型的实例,因此我使用Activator类,如下所示:
(T)Activator.CreateInstance(instance)
我在我的应用程序中使用Autofac作为我的IoC并使用DI。不幸的是,我无法在这些实例中使用DI,因为当我尝试通过构造函数注入它们时,Activator类无法解析依赖项。是否有一种Autofac方法可以做到这一点,但使用我的Autofac注册来解决依赖关系呢?谢谢。
Type customType = GetTheRuntimeType();
var builder = new ContainerBuilder();
builder.RegisterType(customType);
InstancePerLifetimeScope()
或As<IInterface>()
等),但这样就可以工作了。
如果在构建容器时没有该类型,则可以选择在事后手动注入属性。 这有点像服务定位,但这意味着您可以将类型创建与其它操作分开。Type customType = GetTheRuntimeType();
var builder = new ContainerBuilder();
// register everything else, then
var container = builder.Build();
using(var scope = container.BeginLifetimeScope())
{
var instance = Activator.CreateInstance(customType);
scope.InjectUnsetProperties(instance);
}
IEnumerable<T>
这样的东西的方式,即当您从未显式地注册时。您可以提供任何一组运行时类型,并且所有这些类型都可以使用注册源动态插入到容器中。
return (T)scope.Resolve(instance);
- odannycResolve
只是一个泛型,需要传递一个具体的类型参数,例如:Resolve<SomeClass>()
。但实际上我们也可以通过传递一个类型来进行解析,类似这样:Resolve(runtimeType)
。 - odannyc