ASP.NET Module Dependency Injection
During the design of a new generic authentication framework for some of our products, I have come across an architectural issue I cannot seem to find a good solution for.
I have tried 开发者_如何转开发to simplify the problem in order to easily explain it.
The library has two classes:
Manager Is responsible for storing currently authenticated users.
Module It is the responsibility for the module to validate each request according to security policies. The Module must ask the manager to determine whether a user is currently authenticated.
Now the manager is supplied an implementation of an interface which allows the manager to load users from a repository. The specific implementation is not contained in this library. Because of this, I cannot directly instantiate an instance of the repository within the library.
I have no way of modifying properties or supplying arguments for the module constructor. So my question is this, how can I give the module a reference to an instance of the Manager?
namespace Demo
{
public interface IRepository
{
object GetUser(int id);
}
public class Manager
{
public IRepository Repository { get; private set; }
public Manager(IRepository repository)
{
this.Repository = repository;
}
}
public class Module : IHttpModule
{
// How can i access an instance of the manager class here
// when I am unable to instantiate an instance of
// of an implementation of the IRepository interface.
}
}
In classic ASP.NET, I prefer to implement an interface on my HttpApplication
(Global
) that declares the necessary dependencies. Here, it's IHasManager
(the app was written by lolcats):
public class Module: IHttpModule {
Manager manager;
public void Init(HttpApplication context) {
IHasManager application = context as IHasManager;
if (application != null) {
manager = application.Manager;
}
}
}
One of the simplest (if ugly) ways is to stuff your Manager instance into application dictionary after you create it:
HttpContext.Current.Application["Demo.Manager"] = new Manager(new Repository());
Now you can access it in your module with:
var manager = HttpContext.Current.Application["Demo.Manager"] as Manager;
Take a look at this.
think it should do what you need
http://ninject.org/
精彩评论