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.
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
ViewModelLocatoris part of your infrastructure and you never use it directly in your application code … maybe. Please see my comment on @MikePost’s question.