如何获取unitycontainer的实例?
我正在开发一个 Silverlight 应用程序,并将 Unity
引入其中。
我遇到的问题是我不知道如何获取容器的实例。
我在 App
上的 ApplicationStartup
方法中创建了这个实例
_container = new UnityContainer();
_container.RegisterType<IMyAppServiceAgent, MyAppServiceAgent>(new InjectionConstructor(OriginalHandlerId, W2OGuid, ServiceEndpointAddr));
,并编写了一个 getter
public IUnityContainer Container
{
get { return _container; }
}
一切正常,这就是我使用容器的方式:
public static void CreateMemberSearch()
{
if (_memberSearch == null)
{
_memberSearch =
new MemberSearchViewModel((App.Current as App).Container.Resolve<IMyAppServiceAgent>());
}
}
上面的示例来自 ViewModelLocator (来自 MVVM Light 工具包
)。
我需要知道如何重构我的代码以符合 IOC 原则。
I've developing a Silverlight application, and I've introduced Unity
into it.
The problem I have is I don't know how to get an instance of container.
I create this intance in ApplicationStartup
method on the App
_container = new UnityContainer();
_container.RegisterType<IMyAppServiceAgent, MyAppServiceAgent>(new InjectionConstructor(OriginalHandlerId, W2OGuid, ServiceEndpointAddr));
and I write a getter
public IUnityContainer Container
{
get { return _container; }
}
Everything works fine, and this how I use my container:
public static void CreateMemberSearch()
{
if (_memberSearch == null)
{
_memberSearch =
new MemberSearchViewModel((App.Current as App).Container.Resolve<IMyAppServiceAgent>());
}
}
Above example is from ViewModelLocator (from MVVM Light Toolkit
).
I need to know how to refactor my code to go along with the IOC
principles.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上面显示的代码实现了 ServiceLocator 反模式。您永远不应该直接调用容器。
该容器设置在 Composition Root 中。对于 Silverlight 应用程序,这将是您的 ApplicationStartup 方法或专用引导程序,如 Caliburn.Micro 中的那样。
该容器实例仅被调用一次来解析您的主视图或视图模型(取决于您是使用视图优先还是视图模型优先方法)。
应该就是这样。你不应该再调用你的容器。如果某个类依赖于某个其他组件:使用构造函数注入注入该组件。如果该类需要创建其他对象:注入工厂。 Unity 有一个很好的功能,称为自动工厂
更新
如果
ViewModelLocator
是您的基础设施的一部分,您永远不会在应用程序代码中直接使用它......也许吧。请参阅我对@MikePost 问题的评论。The code shown above implements the ServiceLocator anti-pattern. You should never call the container directly.
The container is setup in the Composition Root. For a Silverlight application that would be your ApplicationStartup method or a dedicated bootstrapper like in Caliburn.Micro.
This container instance is called exactly once to resolve your main view oder viewmodel (depending on wether you use a view first or viewmodel first approach).
And that should be it. You should never call your container again. If a class depends on some other component: inject that component using constructor injection. If that class needs to create other objects: inject a factory. Unity has a nice feature called automatic factories
Update
If the
ViewModelLocator
is part of your infrastructure and you never use it directly in your application code ... maybe. Please see my comment on @MikePost's question.