gpt4 book ai didi

c# - 向所有类型注入(inject)具有特定值的字符串参数

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:40 25 4
gpt4 key购买 nike

给定

interface IFoo ...
class MyClass1 : IFoo
{
public MyClass1(string id) ...
}

class MyClass2 : IFoo
{
public MyClass2(string id) ...
}
//new classes will be added

当我解析类时:

UnityContainer container = ...;
container.Resolve(typeThatImplementsIFoo);

那么我如何设置 UnityContainer 以便它在解析任何实现 IFoo 的类时将值 "123" 注入(inject)任何 ctor 参数 "string id"

最佳答案

如果您编写自定义 BuilderStrategy 将覆盖您类的构造函数中的输入参数,则可以做到这一点。

我写了一个测试类来简化。它们与您的类(class)相似:

    public interface IFoo {}

public class MyClass : IFoo
{
public string Id;

public MyClass(string id)
{
Id = id;
}
}

public class MyClass2 : IFoo
{
public string Id;

public MyClass2(string id)
{
Id = id;
}
}

它们是自定义的 BuilderStrategy 和自定义的 UnityContainerExtension:

    public class UnityExtension<TInterface> : UnityContainerExtension
{
private readonly string _paramName;
private readonly object _paramValue;

public UnityExtension(string paramName, object paramValue)
{
_paramName = paramName;
_paramValue = paramValue;
}

protected override void Initialize()
{
var strategy = new BuildStrategy<TInterface>(_paramName, _paramValue);
Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);
}
}

public class BuildStrategy<TInterface> : BuilderStrategy
{
private readonly string _paramName;
private readonly object _paramValue;

public BuildStrategy(string paramName, object paramValue)
{
_paramName = paramName;
_paramValue = paramValue;
}

public override void PreBuildUp(IBuilderContext context)
{
if (typeof(TInterface).IsAssignableFrom(context.OriginalBuildKey.Type))
{
context.AddResolverOverrides(new ParameterOverride(_paramName, _paramValue));
}
}
}

您需要自定义 UnityContainerExtension,因为您无法在没有反射的情况下从 UnityContainer 访问 BuilderStrategy 的集合。

因此您只需将此扩展添加到 UnityContainer 并尝试解析您想要的类型:

    var container = new UnityContainer();
container.AddExtension(new UnityExtension<IFoo>("id", "123"));

var class1 = container.Resolve<MyClass>();
var class2 = container.Resolve<MyClass2>();

// show 123
Console.WriteLine(class1.Id);

// show 123
Console.WriteLine(class2.Id);

关于c# - 向所有类型注入(inject)具有特定值的字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45376270/

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