I using MVC4 and DependencyResolver with Unity. Like in Brad Wilson's blog page http://bradwilson.typepad.com/blog/2010/07/service-location-pt3-views.html, i want to use dependency injection for my views. But it seems that MVC4 view engine does not attempt to create the view page classes via the DependencyResolver. Does it, or maybe i do something wrong? Here is my code:

public static void Register() {
        var unity = new UnityContainer();
        unity.RegisterType<SpaceProject.Models.SpaceShipEntities>(new RequestLifetimeManager());
        DependencyResolver.SetResolver(new UnityDependencyResolver(unity));

}

public abstract class SharedView : WebViewPage
{
    [Dependency]
    public SpaceProject.Models.SpaceShipEntities Context { set; get; }
}

and my _Layout.cshtml:

@inherits SharedView
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
<head></head>
    <body>
    @foreach (var menu in Context.Menu) { 
                            <li>
                                <a href="#">@menu.Title</a> |
                            </li>    
                        }
    </body>
    </html>

I have error that Context is null.

有帮助吗?

解决方案

@inherits SharedView not work in _Layout.cshtml, i think because it is not view and used like Master Page. In views and partial views all works perfect.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top