gpt4 book ai didi

dependency-injection - 统一 IoC : "Operation could destabilize the runtime"

转载 作者:行者123 更新时间:2023-12-04 08:19:56 25 4
gpt4 key购买 nike

是否可以在 UnityContainer 中配置的另一种类型的构造函数中实例化在 UnityContainer 中配置的类型?使用我当前的解决方案,我得到了一个

ResolutionFailedException:
Resolution of the dependency failed, type = "Sample.IMyProcessor", name = "(none)".
Exception occurred while: while resolving.
Exception is: VerificationException - Operation could destabilize the runtime.

问题是我的第二个类 (FileLoader) 有一个应该在第一个构造函数中计算的参数:

MyProcessor 类的构造函数:

public class MyProcessor : IMyProcessor
{
private readonly IFileLoader loader;
private readonly IRepository repository;

public MyProcessor(IRepository repository, string environment, Func<SysConfig, IFileLoader> loaderFactory)
{
this.repository = repository;
SysConfig config = repository.GetConfig(environment);

loader = loaderFactory(config);
}

public void DoWork()
{
loader.Process();
}
}

这里是带有 UnityContainer 配置的 Main 函数:

public static void Run()
{
var unityContainer = new UnityContainer()
.RegisterType<IRepository, MyRepository>()
.RegisterType<IFileLoader, FileLoader>()
.RegisterType<IMyProcessor, MyProcessor>(new InjectionConstructor(typeof(IRepository), "DEV", typeof(Func<SysConfig, IFileLoader>)));

//Tests
var x = unityContainer.Resolve<IRepository>(); //--> OK
var y = unityContainer.Resolve<IFileLoader>(); //--> OK

var processor = unityContainer.Resolve<IMyProcessor>();
//--> ResolutionFailedException: "Operation could destabilize the runtime."

processor.DoWork();
}

还有 FileLoader 类:

public class FileLoader : IFileLoader
{
private readonly SysConfig sysConfig;

public FileLoader(SysConfig sysConfig, IRepository repository)
{
this.sysConfig = sysConfig;
}

public void Process()
{
//some sample implementation
if (sysConfig.IsProduction)
Console.WriteLine("Production Environement");
else
Console.WriteLine("Test Environment");
}
}

我假设问题与传递给 MyProcessor 类的 Func 有关。还有另一种方法可以将 loaderFactory 传递给 MyProcessor 类吗?

谢谢!

最佳答案

问题是 Unity 自动工厂只支持 Func<T>而不是任何其他 Func 泛型。

你可以在Unity中注册你想要的Func,然后它就会解析:

Func<SysConfig, IFileLoader> func = config => container.Resolve<IFileLoader>();
container.RegisterType<Func<SysConfig, IFileLoader>>(new InjectionFactory(c => func));

var processor = container.Resolve<IMyProcessor>();

还有一些其他解决方案,例如:Unity's automatic abstract factory

关于dependency-injection - 统一 IoC : "Operation could destabilize the runtime",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19595179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com