小木猫

标题: 3: Managing Dependencies Between Components Using the Prism Library 5.0 for WPF [打印本页]

作者: admin    时间: 2015-8-23 10:31
标题: 3: Managing Dependencies Between Components Using the Prism Library 5.0 for WPF
3: Managing Dependencies Between Components Using the Prism Library 5.0 for WPF

From: Developer's Guide to Microsoft Prism Library 5.0 for WPF

[size=1em]On this page

Applications based on the Prism Library are composite applications that potentially consist of many loosely coupled types and services. They need to interact to contribute content and receive notifications based on user actions. Because they are loosely coupled, they need a way to interact and communicate with one another to deliver the required business functionality. To tie together these various pieces, applications based on the Prism Library rely on a dependency injection container.

Dependency injection containers reduce the dependency coupling between objects by providing a facility to instantiate instances of classes and manage their lifetime based on the configuration of the container. During the objects creation, the container injects any dependencies that the object requires into it. If those dependencies have not yet been created, the container creates and resolves their dependencies first. In some cases, the container itself is resolved as a dependency. For example, when using the Unity Application Block (Unity) as the container, modules have the container injected, so they can register their views and services with that container.

There are several advantages of using a container:

In the context of an application based on the Prism Library, there are specific advantages to a container:

Note: Some samples in the Prism guidance rely on the Unity Application Block (Unity) as the container. Other code samples, for example the Modularity QuickStarts, use Managed Extensibility Framework (MEF). The Prism Library itself is not container-specific, and you can use its services and patterns with other containers, such as Castle Windsor, StructureMap, and Spring.NET.

Key Decision: Choosing a Dependency Injection Container

The Prism Library provides two options for dependency injection containers: Unity or MEF. Prism is extensible, thereby allowing other containers to be used instead with a little bit of work. Both Unity and MEF provide the same basic functionality for dependency injection, even though they work very differently. Some of the capabilities provided by both containers include the following:

Unity provides several capabilities that MEF does not:

MEF provides several capabilities that Unity does not:

The containers have differences in capabilities and work differently, but the Prism Library will work with either container and provide similar functionality. When considering which container to use, keep in mind the preceding capabilities and determine which fits your scenario better.

Considerations for Using the Container

You should consider the following before using containers:

Note:
Some containers, such as MEF, cannot be configured via a configuration file and must be configured via code.


Core Scenarios

Containers are used for two primary purposes, namely registering and resolving.

Registering

Before you can inject dependencies into an object, the types of the dependencies need to be registered with the container. Registering a type typically involves passing the container an interface and a concrete type that implements that interface. There are primarily two means for registering types and objects: through code or through configuration. The specific means vary from container to container.

Typically, there are two ways of registering types and objects in the container through code:

Registering Types with the Unity Container

During initialization, a type can register other types, such as views and services. Registration allows their dependencies to be provided through the container and allows them to be accessed from other types. To do this, the type will need to have the container injected into the module constructor. The following code shows how the OrderModule type in the Commanding QuickStart registers a type.

[url=]C#[/url]



// OrderModule.cspublic class OrderModule : IModule{    public void Initialize()    {        this.container.RegisterType<IOrdersRepository, OrdersRepository>(new ContainerControlledLifetimeManager());        ...    }    ...}


Depending on which container you use, registration can also be performed outside the code through configuration. For an example of this, see Registering Modules using a Configuration File in Modular Application Development.

Note:
The advantage of registering in code, compared to configuration, is that the registration happens only if the module loads.


Registering Types with MEF

MEF uses an attribute-based system for registering types with the container. As a result, adding type registration to the container is simple: it requires the addition of the [Export] attribute to a type as shown in the following code example.

[url=]C#[/url]



[Export(typeof(ILoggerFacade))]public class CallbackLogger: ILoggerFacade{}


Another option when using MEF is to create an instance of a class and register that particular instance with the container. The QuickStartBootstrapper in the Modularity with MEF QuickStart shows an example of this in theConfigureContainer method, as shown here.

[url=]C#[/url]



protected override void ConfigureContainer(){    base.ConfigureContainer();    // Because we created the CallbackLogger and it needs to     // be used immediately, we compose it to satisfy any imports it has.    this.Container.ComposeExportedValue<CallbackLogger>(this.callbackLogger);}


Note:
When using MEF as your container, it is recommended that you use attributes to register types.


Resolving

After a type is registered, it can be resolved or injected as a dependency. When a type is being resolved, and the container needs to create a new instance, it injects the dependencies into these instances.

In general, when a type is resolved, one of three things happens:

Resolving Instances with Unity

The following code example from the Commanding QuickStart shows where the OrdersEditorView and OrdersToolBarviews are resolved from the container to associate them to the corresponding regions.

[url=]C#[/url]



// OrderModule.cspublic class OrderModule : IModule{    public void Initialize()    {        this.container.RegisterType<IOrdersRepository, OrdersRepository>(new ContainerControlledLifetimeManager());        // Show the Orders Editor view in the shell's main region.        this.regionManager.RegisterViewWithRegion("MainRegion",                            () => this.container.Resolve<OrdersEditorView>());        // Show the Orders Toolbar view in the shell's toolbar region.        this.regionManager.RegisterViewWithRegion("GlobalCommandsRegion",                            () => this.container.Resolve<OrdersToolBar>());    }    ...}


The OrdersEditorViewModel constructor contains the following dependencies (the orders repository and the orders command proxy), which are injected when it is resolved.

[url=]C#[/url]



// OrdersEditorViewModel.cspublic OrdersEditorViewModel(IOrdersRepository ordersRepository, OrdersCommandProxy commandProxy){    this.ordersRepository = ordersRepository;    this.commandProxy     = commandProxy;    // Create dummy order data.    this.PopulateOrders();    // Initialize a CollectionView for the underlying Orders collection.    this.Orders = new ListCollectionView( _orders );    // Track the current selection.    this.Orders.CurrentChanged += SelectedOrderChanged;    this.Orders.MoveCurrentTo(null);}


In addition to the constructor injection shown in the preceding code, Unity also allows for property injection. Any properties that have a [Dependency] attribute applied are automatically resolved and injected when the object is resolved.

Resolving Instances with MEF

The following code example shows how the Bootstrapper in the Modularity with MEF QuickStart obtains an instance of the shell. Instead of requesting a concrete type, the code could request an instance of an interface.

[url=]C#[/url]



protected override DependencyObject CreateShell(){    return this.Container.GetExportedValue<Shell>();}


In any class that is resolved by MEF, you can also use constructor injection, as shown in the following code example from ModuleA in the Modularity with MEF QuickStart, which has an ILoggerFacade and an IModuleTracker injected.

[url=]C#[/url]



[ImportingConstructor]public ModuleA(ILoggerFacade logger, IModuleTracker moduleTracker){    if (logger == null)    {        throw new ArgumentNullException("logger");    }    if (moduleTracker == null)    {        throw new ArgumentNullException("moduleTracker");    }    this.logger = logger;    this.moduleTracker = moduleTracker;    this.moduleTracker.RecordModuleConstructed(WellKnownModuleNames.ModuleA);}


Another option is to use property injection, as shown in the ModuleTracker class from the Modularity with MEF QuickStart, which has an instance of the ILoggerFacade injected.

[url=]C#[/url]



[Export(typeof(IModuleTracker))]public class ModuleTracker : IModuleTracker{     [Import] private ILoggerFacade Logger;}


Using Dependency Injection Containers and Services in Prism

Dependency injection containers, often referred to as just "containers," are used to satisfy dependencies between components; satisfying these dependencies typically involves registration and resolution. The Prism Library provides support for the Unity container and for MEF, but it is not container-specific. Because the library accesses the container through the IServiceLocator interface, the container can be replaced. To do this, your container must implement theIServiceLocator interface. Usually, if you are replacing the container, you will also need to provide your own container-specific bootstrapper. The IServiceLocator interface is defined in the Common Service Locator Library. This is an open source effort to provide an abstraction over IoC (Inversion of Control) containers, such as dependency injection containers, and service locators. The objective of using this library is to leverage IoC and Service Location without tying to a specific implementation.

The Prism Library provides the UnityServiceLocatorAdapter and the MefServiceLocatorAdapter. Both adapters implement the ISeviceLocator interface by extending the ServiceLocatorImplBase type. The following illustration shows the class hierarchy.


The Common Service Locator implementations in Prism

Although the Prism Library does not reference or rely on a specific container, it is typical for an application to rely on a specific container. This means that it is reasonable for a specific application to refer to the container, but the Prism Library does not refer to the container directly. For example, the Stock Trader RI and several of the QuickStarts included with Prism rely on Unity as the container. Other samples and QuickStarts rely on MEF.

IServiceLocator

The following code shows the IServiceLocator interface.

[url=]C#[/url]



public interface IServiceLocator : IServiceProvider{    object GetInstance(Type serviceType);    object GetInstance(Type serviceType, string key);    IEnumerable<object> GetAllInstances(Type serviceType);    TService GetInstance<TService>();    TService GetInstance<TService>(string key);    IEnumerable<TService> GetAllInstances<TService>();}


The Service Locator is extended in the Prism Library with the extension methods shown in the following code. You can see that IServiceLocator is used only for resolving, meaning it is used to obtain an instance; it is not used for registration.

[url=]C#[/url]



// ServiceLocatorExtensionspublic static class ServiceLocatorExtensions{    public static object TryResolve(this IServiceLocator locator, Type type)    {        try        {            return locator.GetInstance(type);        }        catch (ActivationException)        {            return null;        }    }    public static T TryResolve<T>(this IServiceLocator locator) where T: class    {        return locator.TryResolve(typeof(T)) as T;    }}


The TryResolve extension method—which the Unity container does not support—returns an instance of the type to be resolved if it has been registered; otherwise, it returns null.

The ModuleInitializer uses IServiceLocator for resolving the module during module loading, as shown in the following code examples.

[url=]C#[/url]



// ModuleInitializer.cs - Initialize()IModule moduleInstance = null;try{    moduleInstance = this.CreateModule(moduleInfo);    moduleInstance.Initialize();}...


[url=]C#[/url]



// ModuleInitializer.cs - CreateModule()protected virtual IModule CreateModule(string typeName){    Type moduleType = Type.GetType(typeName);    if (moduleType == null)    {        throw new ModuleInitializeException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.FailedToGetType, typeName));    }    return (IModule)this.serviceLocator.GetInstance(moduleType);}


Considerations for Using IServiceLocator

IServiceLocator is not meant to be the general-purpose container. Containers have different semantics of usage, which often drives the decision for why that container is chosen. Bearing this in mind, the Stock Trader RI uses the dependency injection container directly instead of using the IServiceLocator. This is the recommend approach for your application development.

In the following situations, it may be appropriate for you to use the IServiceLocator:

More Information

For information related to containers, see the following:



Next Topic | Previous Topic | Home | Community


作者: gydwc3b安凱呈k    时间: 2015-10-2 21:13
谢了.学习中,先顶













明星手记
最新汽车大全
百分百明星图库大全
最新国际形式
红旗渠香烟价格表图
随身带着番茄园
天子香烟价格表图
台州新闻播报
无限之末日法则
最后的霸气
港台明星
浙江高校与基础教育
国际事物
绍兴新闻
恒大香烟价格
明星大咖
当红小生
明星达人
狗仔爆料
妖女养成计划

作者: gydwc3b安凱呈k    时间: 2015-10-3 03:56
很好,谢谢你啊,辛苦了~~













宁波新闻
不败军神
万世浩劫
茶花香烟哪里有卖
我爱上了老婆
最新艳照门
欧美图片
娱乐百分百
花田喜嫁,拐个狼王当相公
神夜
墨砚
香港四大天王
娱乐八卦
梦境边缘
红豆香烟
浙江体育发展
台州新闻
明星毒舌
嘉兴新闻
海洋香烟

作者: gydwc3b安凱呈k    时间: 2015-10-5 01:17
非常感谢您!













我从大唐来之千年情
独家娱乐
人民大会堂香烟价格
台州新闻
明星艳照门
哈尔滨香烟
八卦爆料
真实的天空
林海灵芝香烟
盗尽桃花
火影之水中无月
变异生物系统
浙江房价动态
独家娱乐
浙江科技
仙路扶摇
呼伦贝尔香烟
女神档案室
苦苦
浙江旅游

作者: gydwc3b安凱呈k    时间: 2015-10-5 13:02
看的激动。。。 谢谢楼主了













癫痫发作的急救
癫痫病的发作
癫痫小发作如何处理
癫痫病治疗药物
癫痫的常见症状有哪些
癫痫小发作
治疗癫痫病最好的药物
癫痫病的最新治疗方法怎么样
小儿脑瘫怎么治疗好
癫痫治疗
治疗癫痫的药物
癫痫治疗
羊癫疯是什么引起的
治疗癫痫病的药物
癫痫病的发作症状
癫痫病发作怎么办
脑外伤癫痫病
儿童癫痫小发作
治疗癫痫的偏方
癫痫病的治疗偏方

作者: gydwc3b安凱呈k    时间: 2015-10-5 13:29
如果能给大家带来好处也不错。













http://amdcwzdq61.hbaftdt.com/forum.php?mod=viewthread&tid=2261488
http://www.112008.com/forum.php?mod=viewthread&tid=118090
http://www.sxtxh.net/forum.php?mod=viewthread&tid=92370
http://www.haohangroup.com.cn/forum.php?mod=viewthread&tid=462921
http://wxmgc.cn/read.php?tid=243987&fid=3
http://hjdcwz00.hbaftdt.com/forum.php?mod=viewthread&tid=2261485
http://airobot.top/thread-86120-1-1.html
http://www.wxmgc.cn/read.php?tid=243986&fid=4
http://lamabang.org/forum.php?mod=viewthread&tid=85579
http://fengshao.me/forum.php?mod=viewthread&tid=401891
http://bbs.as87.com/forum.php?mod=viewthread&tid=107527
http://www.tiine.com/thread-43322-1-1.html
http://kdcdtj56.jlfadianji.com/forum.php?mod=viewthread&tid=1173311
http://pjdctp24.hbaftdt.com/forum.php?mod=viewthread&tid=2261481
http://www.365juw.com/thread-185818-1-1.html
http://www.atxrecords.com/forum.php?mod=viewthread&tid=44416
http://jiazhangweixiao.com/thread-141197-1-1.html
http://huihai.ccbuild.com/forum.php?mod=viewthread&tid=190023
http://bbs.dexuehui.com/forum.php?mod=viewthread&tid=212337
http://www.51shangan.cn/forum.php?mod=viewthread&tid=357581





欢迎光临 小木猫 (https://woodenkitten.com/) Powered by Discuz! X3.2