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

瀏覽次數:35 次
跳到第一則未讀訊息

Kevin Labranche

未讀,
2021年3月30日 晚上7:30:192021/3/30
收件者: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

未讀,
2021年3月31日 清晨5:01:252021/3/31
收件者: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

未讀,
2021年3月31日 上午10:00:532021/3/31
收件者: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

未讀,
2021年3月31日 上午10:42:022021/3/31
收件者: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

回覆所有人
回覆作者
轉寄
0 則新訊息