I’m using Structure map and want to inject instance (constructed by container) into controller’s property. Instance should be named and stored in http session context container.
In the previous version of my application I’ve used custom DI framework and it was easy enough to make such things:
public class MyController : Controller
{
[InjectSession("MySessionInstanceKey")]
public MyManager Manager {get; set;}
}
Is there any easy ways to do it with structuremap ?
Or maybe i can introduce my custom attributes and injection logic into SM framework (extend framework somehow) ?
Please help me to find a way to resolve this and Thanks a lot !
P.S. i’ve found temporary solution, but it increases cohesion of controller with IoC framework and contains a lot of code:
private const string ordersBulkManagerKey = "_OrdersBulkManager";
public BulkManager OrdersBulkManager
{
get
{
var manager = Session[ordersBulkManagerKey] as BulkManager;
if(manager == null)
Session[ordersBulkManagerKey] = manager
= ObjectFactory.GetInstance<BulkManager>();
return manager;
}
}
So, I don’t want to use ObjectFactory.GetInstance there …
There’s a few blog post out there on how to wire up configure ASP.NET MVC and StructureMap together. (So most of the following code is a summary from various posts out there.)
The common way to get this going is by declaring our own controller factory class, which will allow us inject our dependencies via the constructor. (The default controller factory that ASP.NET MVC uses requires a default constructor to be present)
So in your MyController class, you would have a constructor which accept a MyManager parameter (which will be injected for you by our very own controller factory class)
Next you would configure ASP.NET MVC do use this new controller factory class (which we will call StructureMapControllerFactory).
In the StructureMapControllerFactory, we call ObjectFactory.GetInstance to you return us the controller (provided we have wired up all our dependencies)
Hopefully my explanation is clear, but let me know if it isn’t and I can expand on it.
BTW, the snippet below is an example on how your bootstrap code might look like.
Note: Please refer to StructureMap doc for various InstanceScope options.