问题
I've been struggling with the ideal approach to this. Right now, I have my services created in Boostrapper right before I create my application shell, in the method:
protected override DependencyObject CreateShell()
After my shell gets created, I then create all my view models, passing the services they need.
So firstly, I want to know if that's a good practice. Also, I've tried to find examples of declaring services inside a .config file, but I really didn't see any. Is this not a good practice either?
Example:
protected override DependencyObject CreateShell()
{
appWnd = ServiceLocator.Current.GetInstance<ApplicationWindow>();
Container.RegisterInstance<ILicensing>(new LicensingService());
Container.RegisterInstance<IAnotherService>(new AnotherService());
return appWnd;
}
回答1:
The method ConfigureContainer() of the UnityBootstrapper is supposed to be overridden to do what you are asking for:
MSDN - ConfigureContainer:
Both the Composite Application Library and the applications built on top of it depend on a container for injecting required dependencies. During the container configuration phase, several core services are registered, as shown in the following code from the UnityBootstrapper.
MSDN on UnityBootstrapper
The MSDN example:
protected virtual void ConfigureContainer()
{
…
if (useDefaultConfiguration)
{
RegisterTypeIfMissing(typeof(IServiceLocator), typeof(UnityServiceLocatorAdapter), true);
RegisterTypeIfMissing(typeof(IModuleInitializer), typeof(ModuleInitializer), true);
RegisterTypeIfMissing(typeof(IModuleManager), typeof(ModuleManager), true);
RegisterTypeIfMissing(typeof(RegionAdapterMappings), typeof(RegionAdapterMappings), true);
RegisterTypeIfMissing(typeof(IRegionManager), typeof(RegionManager), true);
RegisterTypeIfMissing(typeof(IEventAggregator), typeof(EventAggregator), true);
RegisterTypeIfMissing(typeof(IRegionViewRegistry), typeof(RegionViewRegistry), true);
RegisterTypeIfMissing(typeof(IRegionBehaviorFactory), typeof(RegionBehaviorFactory), true);
}
}
You can also register instances here, etc., using Container
directly, as you already do.
The CreateShell() method is not the place to do this, as you should do nothing more than creating the shell here.
So, in short, just override ConfigureCatalog() and paste your code there.
来源:https://stackoverflow.com/questions/15231652/when-should-my-prism-services-be-registered