HongyanShen
HongyanShen

Reputation: 1535

In dotnet mvc 5, how to inject a service into a view?

In dotnet core mvc,i can inject a service into a view by using @inject directive,but how to do this in dotnet mvc 5.It seems that there is no @inject directive in mvc 5.

Upvotes: 10

Views: 4350

Answers (1)

Fab
Fab

Reputation: 14813

ASP.NET MVC 5 doesn't have @inject

This keyword only exists in ASP.NET Core.

Work-around using @model

However you can still inject a dependency in the controller and from the controller pass it to the model. @model and @Model can be used freely in the razor page/view.

MyController.cs:

public class MyController : Controller
{
    public MyController(IMyDependency dependency)
    {
        _dependency = dependency;
    }

    public ActionResult Index()
    {
        View(new ViewModel
        {
            Dependency = _dependency
        });
    }
}

Razor.cshtml:

@model ViewModel

@if (Model.Dependency.CanView)
{
    <!-- Put the code here -->
}

It also means you can put a IServiceProvider in the model and resolve directly in the view. However, in terms of separation of concerns, it's not the ideal.

Upvotes: 9

Related Questions