2

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?

1
  • Why don't you use constructor injection in your HomeController? This way you can remove the dependency on the Unity container from within your application. Commented May 11, 2011 at 12:54

1 Answer 1

2

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>(); 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! i tried this but there is still a problem. Some of the session variables such as loggedinuser,etc are actually initialized in my account controller that performs the authentication. The _container.RegisterType called is currently in the Application_Start() event of global.asax so the problem i get it when unity tries to resolve the dependency right at the start,in the AspNetUserContext class, the HttpContext.Current.Session is null at this point. Is there any way i can do a delay load here so that this call is made after the authentication has been done.
@user748526: Unity will not call the properties on the AspNetUserContext class, so as long as you don't use the properties when the user is not authenticated, there should not be a problem. You could even add a IsUserAuthenticated property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.