如何获取在Unity中注入的对象的类型? [英] How to get the type of the object that is being injected in Unity?

查看:325
本文介绍了如何获取在Unity中注入的对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a type that receives another type in its constructor, which usually is the type of the object that creates it, e.g.:

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

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

I would like to instruct Unity to resolve Logger passing as the argument to its constructor the type of the object that requires it. Something like:

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

因此,当我尝试解析 MyService

So that when I try to resolve MyService:

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

它将返回:

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

有可能吗?

推荐答案

实际上,您可以这样做:

Actually, you can do this:

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 )
    {
    }
}

这仅是概念验证代码,可能需要在生产使用之前进行一些改进...

This is proof of concept code only, and might need to be refined a bit before production use...

这篇关于如何获取在Unity中注入的对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆