In ASP.NET MVC you can even apply dependency injection into views. You can use the IoC framework of your choice and injecting Dependencies into your views will just work.
Most of the time I create a base class to inject some common dependencies:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class InjectedWebViewPage : WebViewPage | |
{ | |
[Dependency] | |
public IAppSettings Settings { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<system.web.webPages.razor> | |
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> | |
<pages pageBaseType="MyApp.Custom.InjectedWebViewPage"> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@{ | |
ViewBag.Title = "Home Page"; | |
Layout = "~/Views/Shared/_Layout.cshtml"; | |
} | |
<h2>@ViewBag.Message</h2> | |
Please contact us at @Settings.EmailAddress |
Remark: The only thing you need to be aware of is that the Dependency injection does not work inside your layout view.