1

如果我有这样的事情:

        var container = new Container();
        container.RegisterInstance("a", serviceKey: "a");
        container.RegisterInstance("b", serviceKey: "b");

如何注册包含“a”和“b”的字符串列表?

我也尝试使用参数但没有成功。

    class T
    {
        public string[] x;

        public T(string s, params string[] strs)
        {
            x = (new[] {s}).Union(strs).ToArray();
        }
    }

    static void Main(string[] args)
    {
        var container = new Container();
        container.RegisterInstance("a", serviceKey: "a");
        container.RegisterInstance("b", serviceKey: "b");
        container.Register<T>(made: Made.Of(() => new T(Arg.Of<string>("a"))));
        container.Register<T>(made: Made.Of(() => new T(Arg.Of<string>("a"), Arg.Of<string>("b"))));

编辑:

我设法让它运行,但它可能不是一个好的解决方法:

        container.RegisterInstance(typeof(IEntityManager), (IEntityManager)ctx.GetObject("entityManager_candidate"), serviceKey: "candidate");
        container.RegisterInstance("XYZ_CANDIDATE", serviceKey: "candidate");
        container.Register<IDalCandidate>(serviceKey: "candidate",
            made: Made.Of(() => new DalCandidate(Arg.Of<IEntityManager>("candidate"), Arg.Of<string>("candidate"))));
        container.RegisterInstance(typeof(IEntityManager), (IEntityManager)ctx.GetObject("entityManager_resource"), serviceKey: "resource");
        container.RegisterInstance("XYZ_RESOURCE", serviceKey: "resource");
        container.Register<IDalCandidate>(serviceKey: "resource",
            made: Made.Of(() => new DalCandidate(Arg.Of<IEntityManager>("resource"), Arg.Of<string>("resource"))));
        //container.RegisterMapping<IDalCandidate, DalCandidate>()
        var lst = new List<IDalCandidate>
        {
            container.Resolve<IDalCandidate>("resource"),
            container.Resolve<IDalCandidate>("candidate")
        };
        container.RegisterInstance(typeof(IList<IDalCandidate>), lst);
        container.Register<ISearchWeightedCandidateManager, SearchWeightedCandidateManager>();
4

1 回答 1

1

更新:更好的答案

再次查看您的样本.. 基本上您有某种多租户,然后将所有租户注入某个消费者。

c.Register<Dal>(serviceKey: "x");
c.Register<Dal>(serviceKey: "y");

// using delegate for brevity, better convert to method
Func<object, Func<RequestInfo, bool>> getCondition = 
     key => r => r.Parent.Enumerate().Any(p => p.ServiceKey == key);
var inX = getCondition("x");
var inY = getCondition("y");

c.RegisterInstance("a", condition: inX);
c.RegisterInstance("b", condition: inY);

// register the rest of dependencies in X or in Y

c.Register<Manager>(); // normally injects Dal[]

那就是证明这个想法。希望它比我的第一个答案更适合您的情况。

于 2016-03-25T12:02:56.007 回答