使用Unity注射阵列 [英] Injecting arrays with Unity

查看:135
本文介绍了使用Unity注射阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是构造器注入实现接口的对象的数组。

My goal is to constructor inject an array of objects implementing an interface.

以下是我现在有它的方式。

The following is the way I currently have it.

            Container

                    .RegisterInstance<Company>(ParseCompany(args[1])

                    .RegisterInstance<eTargets>(ParseTargets(args[2]))

                    .RegisterInstance<ILoader[]>(new ILoader[] {
                        Container.Resolve<CustomerLoader>(),
                        Container.Resolve<PaymentLoader(),
                        Container.Resolve<InvoiceLoader() 
                    });

它是典型的呼叫解决容器配置这种方式还是有来完成同样的事情?

Is it typical to call Resolve in container configuration this way or is there a more standard way to accomplish the same thing?

推荐答案

统一的本地了解到阵列,所以没有理由做起来很复杂。只要注册了 ILoaders 要包括和解决对象通常图形。 自动布线会照顾其余的:

Unity natively understands arrays, so there's no reason to make it so complicated. Just register the ILoaders you want to include and resolve the object graphs normally. Auto-wiring will take care of the rest:

container.RegisterType<ILoader, FooLoader>("foo");
container.RegisterType<ILoader, BarLoader>("bar");
container.RegisterType<ILoader, BazLoader>("baz");

var c = container.Resolve<MyConsumer>();



假设 MyConsumer 构造像定义这样的:

public MyConsumer(ILoader[] loaders)

然而,你应该知道,(对于一些深不可测的原因),统一只包含的命名的这样的组件。该的默认的组件:

However, you should be aware that (for some unfathomable reason) Unity only includes named components in this way. The default component:

container.RegisterType<ILoader, Loader>();



会的的被包含在数组中,因为它没有名字。

will not be included in the array, since it has no name.

这篇关于使用Unity注射阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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