Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inject an HTTP-Request-specific object into my Unity supplied object?

For example, I store the "current user" in Session. The business-layer object are being instantiated by Unity. How do I make the business-layer object aware of the "current user"?

like image 978
harley.333 Avatar asked May 02 '13 15:05

harley.333


1 Answers

You should hide the "current user" behind an abstraction:

public interface ICurrentUser
{
    string Name { get; }
}

This abstraction should be defined in the business layer and you need to create an ASP.NET specific implementation that you place in the Composition Root:

public class AspNetCurrentUser : ICurrentUser
{
    public string Name
    {
        get { return HttpContext.Current.Session["user"]; }
    }
}

Now your business-layer object can depend on the ICurrentUser interface, and in Unity you can register the implementation as follows:

container.RegisterType<ICurrentUser, AspNetCurrentUser>();
like image 87
Steven Avatar answered Oct 13 '22 17:10

Steven