假设我们有两个具有相同构造函数的类Injectable依赖: public class FirstClass{ public FirstClass(ISomeDependency someDependency) { }}public class SecondClass{ public SecondClass(ISomeDependency someDependency) { }} 现在我们
public class FirstClass { public FirstClass(ISomeDependency someDependency) { } } public class SecondClass { public SecondClass(ISomeDependency someDependency) { } }
现在我们注册了ISomeDependency:
builder.Register(x => { string key = GetKeyFromCurrentHttpRequest(); // if "Caller" is "FirstClass" return new Dependency(key); // else return new Dependency("defaultKey"); }).As<ISomeDependency>();
注意:这是一个简化的用例.真实场景要复杂得多.
1.如何获得试图解决ISomeDependency的“Caller”类型?
2.有没有更好的方法来设计这种情况?
您可以使用委托工厂来实现您的目标.唯一的缺点是FirstClass和SecondClass不能使用ISomeDependency作为参数.您可以在控制台应用程序中尝试此代码(只需添加Autofac依赖项).
using System; using Autofac; namespace test { class MainClass { public static void Main(string[] args) { ContainerBuilder builder = new ContainerBuilder (); builder.RegisterType<SomeDependency>().As<ISomeDependency>(); builder.RegisterType<FirstClass>(); builder.RegisterType<SecondClass>(); var container = builder.Build(); var dummy = container.Resolve<FirstClass>(); var dummy2 = container.Resolve<SecondClass>(); } public interface ISomeDependency { } public class SomeDependency : ISomeDependency { public delegate ISomeDependency Factory(string value); private readonly string _value; public SomeDependency(string value) { _value = value; Console.WriteLine("Value = " + _value); } } public class FirstClass { private ISomeDependency _dependency; public FirstClass(SomeDependency.Factory factory) { _dependency = factory.Invoke("my value"); } } public class SecondClass { private ISomeDependency _dependency; public SecondClass(SomeDependency.Factory factory) { _dependency = factory.Invoke("my value 2"); } } } }