Possible to inject dependency for layout.cshtml in asp.net mvc5?

25 views
Skip to first unread message

Kevin Labranche

unread,
Mar 30, 2021, 7:30:19 PM3/30/21
to structuremap-users
I have a largish project that I am working to make more palatable for testing AND eventual conversion to core.  I converted a static class that wrapped session state to be  non-static and I have all my controllers that use it injected now.  However, I have my layout.cshtml and a few other layout files that are switched in/out based on the user.

Without resorting to converting everything in these layouts to direct session state access ((bool)Session["SessionVarName"]) is there a way in these views to inject the non-static class now so I can still use my wrapper for access instead (session.SessionVarName)?

Something like this at the top of my layout views:

@{
  ISessionWrapper session;
  var session = StructureMap.Container....GetInstanceOf(...)
}

or perhaps somewhere in the plumbing that I tell MVC that layout has this dependency?

Ryan Heath

unread,
Mar 31, 2021, 5:01:25 AM3/31/21
to structure...@googlegroups.com
Inject into views is not possible in mvc5, (in core it is)
You might want to use good old HttpContext.Items, 
Store your session state into an item of HttpContext.Items (in core this will not work, the HttpContext in views is not necessarily the same as in the controller)

HTH
// Ryan

--
You received this message because you are subscribed to the Google Groups "structuremap-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to structuremap-us...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/structuremap-users/f835f8c6-51ce-4610-92ec-90b8e1801b4cn%40googlegroups.com.

Kevin Labranche

unread,
Mar 31, 2021, 10:00:53 AM3/31/21
to structuremap-users
Thanks, I figured it wasn't possible but wanted to ask.  :-) I'm trying to make it smoother to transition to core.  I'll just have to deal with the layout hitting session directly for now.  Then after upgrade to core I will inject in what I need. :-)  

Kevin Labranche

unread,
Mar 31, 2021, 10:42:02 AM3/31/21
to structuremap-users
There is an easy enough fix.  Can't believe I didn't think of it already.  I have an action filter that all my controllers are using already.  Just added the items I needed in the layout via the viewbag for now.  That removes the original code of using a static class in the layout and other controllers/views which made for harder testing & fixes the layout with an approach that would work in core as well.  Naturally, I will likely look to also use core's injecting of services as well. :-)

Thanks,
Kevin

Reply all
Reply to author
Forward
0 new messages