gpt4 book ai didi

c# - 如何获取在 Unity 中注入(inject)的对象的类型?

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

我有一个类型在其构造函数中接收另一个类型,通常是创建它的对象的类型,例如:

public class Logger {
public Logger(Type parent) { ... }
}

我想指示 Unity 解析 Logger 将需要它的对象的类型作为参数传递给其构造函数。像这样的东西:

// ... would be some directive to tell Unity to use the type that
/// depends on Logger
container.RegisterType<Logger>(new InjectionConstructor(...));

所以当我尝试解析 MyService 时:

public MyService {
public MyService(Logger logger) { ... }
}

它将返回:

var logger = new Logger(typeof(MyService));
return new MyService(logger);

这可能吗?还有其他方法吗?

最佳答案

实际上,你可以这样做:

internal class Program
{
static void Main( string[] args )
{
var container = new UnityContainer();
container.RegisterType<IInterface, Implementation>( new MyInjectionConstructor() );

// this instance will get a logger constructed with loggedType == typeof( Implementation )
var instance = container.Resolve<IInterface>();
}
}

internal class MyInjectionConstructor : InjectionMember
{
public override void AddPolicies( Type serviceType, Type implementationType, string name, IPolicyList policies )
{
policies.Set<IConstructorSelectorPolicy>( new MyConstructorSelectorPolicy(), new NamedTypeBuildKey( implementationType, name ) );
}
}

internal class MyConstructorSelectorPolicy : DefaultUnityConstructorSelectorPolicy
{
protected override IDependencyResolverPolicy CreateResolver( ParameterInfo parameter )
{
if( parameter.ParameterType == typeof( ILogger ) )
{
return new LiteralValueDependencyResolverPolicy( new Logger( parameter.Member.DeclaringType ) );
}
return base.CreateResolver( parameter );
}
}

internal interface ILogger
{
}

internal class Logger : ILogger
{
public Logger( Type loggedType )
{
}
}

internal interface IInterface
{
}

internal class Implementation : IInterface
{
public Implementation( ILogger logger )
{
}
}

这只是概念代码的证明,在生产使用之前可能需要稍微改进一下......

关于c# - 如何获取在 Unity 中注入(inject)的对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43056082/

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