2017-03-27 45 views
1

我具有接收在其構造,這通常是創建它的對象的類型,例如另一種類型的一個類型:如何獲得在Unity中注入的對象的類型?

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

我想指示統一解決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); 

這可能嗎?還有另一種方法嗎?

回答

0

其實,你可以這樣做:

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

這是唯一的概念證明代碼,並且可能需要改進之前生產的使用有點...

相關問題