I thought of applying Dependency Injection and use Unity in the Project I am working on now. Registered the types in Application_Start event of Global.asax file and kept the Unity Conatiner in Application object global variable. However before resolving the presenter instance I need to pass the current webform’s instance as a constructor parameter to the presenter. I am doing this in OnInit event of the page.
protected override void OnInit(EventArgs e)
{
IUnityContainer container = (IUnityContainer)
HttpContext.Current.Application["container"];
container.RegisterInstance<IAddRoleView>(this,
new ExternallyControlledLifetimeManager());
_presenter = container.Resolve<AddRolePresenter>();
base.OnInit(e);
}
My questions here are:
- What will happen to the
AddRoleViewinstance once the Request is
served? - Will it be Garbage Collected or will the Unity container always
keep a reference until application shutdown, as the Unity Conatiner
instance has been kept in an application object?
What you are doing will not work. You are registering the page instance as singleton in the container. This will not work. Depending on how Unity is built, it will either throw an exception the second time you call
RegisterInstance<IAddRoleView>, cache all registered instances forever, or replace the previous implementation. But even if it replaces the previous registration, you have a concurrency bug in your code, since it is possible for a different page to be injected in theAddRolePreventerthat is resolved for thisPageinstance.I understand what you are trying to achieve. Yyou want to resolve the
AddRolePresenter, and want to inject the page into the presenter’s constructor. You made both types dependent on each other through their constructor, which causes a cyclic dependency. You need to break this dependency cycle by injecting the page into a property on the presenter. But don’t let Unity inject the page into the constructor; do this manually:Some tips:
Application_Startran). Adding registrations after the initialization phase is typically considered bad practice, since it makes the configuration brittle, and hard to maintain.