Search code examples
asp.net-mvc-3dependency-injectionunity-container

Unity with asp.net mvc, passing parameters with property injection


I am currently inserting a dependency in my mvc controller as shown below:

public class HomeController : Controller
{
    [Dependency]
    public IProxyService ProxyService { get; set; }
}

In global.asax, the type is registered using

UnityContainer _container = new UnityContainer();
_container.RegisterType<IProxyService, SystemProxyServiceEx>();

Now, I need to pass a few parameters to the SystemProxyServiceEx constructor. These include some values stored in the session variable(HttpSessionStateBase Session) that are stored during authentication. How do I make this happen?


Solution

  • The common thing to do is to wrap those in a class and inject it based on an interface. For instance:

    // This interface lives in a service or base project.
    public interface IUserContext
    {
        string UserId { get; }
    
        // Other properties
    }
    
    // This class lives in your Web App project 
    public class AspNetUserContext : IUserContext
    {
        public string UserId
        {
            get { return (int)HttpContext.Current.Session["Id"]; }
        }
    
        // Other properties
    }
    

    Now you can make your SystemProxyServiceEx take a dependency on IUserContext. Last step is to register it, which of course will be easy:

    _container.RegisterType<IUserContext, AspNetUserContext>();