How do I inject an HTTP-Request-specific object into my Unity supplied object?
asp.net-mvc, asp.net-mvc-4, dependency-injection, unity-container
Solution
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>();
Problem
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"?