Autofac。如何获得调用者类类型?

时间:2015-01-29 17:15:28

标签: dependency-injection inversion-of-control autofac ioc-container

假设我们有两个具有相同构造函数的类,可注入依赖项:

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。是否有更好的方法来设计这种情况?

1 个答案:

答案 0 :(得分:1)

您可以使用委托工厂来实现您的目标。唯一的缺点是FirstClassSecondClass无法使用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");
            }
        }
    }
}