I am doing a project in ASP.NET MVC in which I want to implement an IoC container. I am new to IoC containers and have been searching to find a solution to my problem, but so far to no avail.
The problem is dat data is distributed across various databases. Once a user is logged in, the database for th开发者_如何学编程e user is retrieved from an authorization database and then set in the user session. That user session is passed on to the services and repositories when they are constructed, so they can use it when they need it to access the database.
A typical bare stripped service (without interfaces and ioc) looks like this:
private CompetitionRepository _CompetitionRepo;
public CompetitionService(DataContext dataContext)
: this (new CompetitionRepository(dataContext))
{ }
public CompetitionService(CompetitionRepository competitionRepo)
{
this._CompetitionRepo = competitionRepo;
}
The "DataContext" contains a couple of properties with which the correct database is selected for the session. Because the Services and Repositories don't have access to the session itself (which is outside of their scope) they need this object.
My question is, how can I set something like this up in IoC (doesn't matter which container, I just want to know the general idea). As far as I can see, most containers do not allow objects to be passed in? Or is the design fundamentally flawed?
As far as I can see, most containers do not allow objects to be passed in?
You can't be looking far then ;) Most IoC containers that I know have the ability to do this. You need to register an instance of an object based on its type. How and when that object is constructed is probably a deeper question than the one you've asked. However, to get to the point, you can do something like this with the Unity container:
DataContext context = ..... ;
container.RegisterInstance(context);
Each time you create an instance of a class that requires a DataContext, you'll get the one you've registered. If the type you want to associate the instance with is different, you can force it like so:
container.RegisterInstance<IDataContext>(context);
For more information, take a look here.
精彩评论