1、Registering Types and Objects
Registering Types with the Unity Container
public class OrderModule : IModule
{
public void Initialize()
{
this.container.RegisterType<IOrdersRepository,OrdersRepository>(new
ContainerControlledLifetimeManager());
...
}
...
}
Registering Types with MEF
[Export(typeof(ILoggerFacade))]
public class CallbackLogger: ILoggerFacade
{
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
// Because we created the CallbackLogger and itneeds to
// be used immediately, we compose it to satisfyany imports it has.
this.Container.ComposeExportedValue<CallbackLogger>(this.callbackLogger);
}
Resolving Types andObjects
Resolving Instances with Unity
public class OrderModule : IModule
{
public void Initialize()
{
this.container.RegisterType<IOrdersRepository,OrdersRepository>(new
ContainerControlledLifetimeManager());
// Show the Orders Editor view in the shell’smain region.
this.regionManager.RegisterViewWithRegion("MainRegion",
() =>this.container.Resolve<OrdersEditorView>());
// Show the Orders Toolbar view in the shell’stoolbar region.
this.regionManager.RegisterViewWithRegion("GlobalCommandsRegion",
() => this.container.Resolve<OrdersToolBar>());
}
...
}
Resolving Instances with MEF
[ImportingConstructor]
public ModuleA(ILoggerFacade logger,IModuleTracker moduleTracker)
{
if (logger == null)
{
throw newArgumentNullException("logger");
}
if (moduleTracker == null)
{
throw newArgumentNullException("moduleTracker");
}
this.logger = logger;
this.moduleTracker = moduleTracker;
this.moduleTracker.RecordModuleConstructed(WellKnownModuleNames.ModuleA);
}
[Export(typeof(IModuleTracker))]
public class ModuleTracker : IModuleTracker
{
// Due to Silverlight/MEF restrictions, thismust be public.
[Import] public ILoggerFacade Logger;
}