ASP. Net core MVC dependency injection view and controller

Time:2022-6-22

1、 Asp Net core MVC dependency injection view

  ASP.NET Core Support for dependency injection in attempts. This will help provide view specific services, such as localization or data used only to populate view elements. Try to keep the separation of concerns between the controller and the view. Most of the data displayed by the view should be passed in from the controller.

Use@injectInstruction to inject service into view, syntax@inject <type> <name> 

For example:


@model MVCTest.Models.Operation
@using MVCTest.Services
@inject BaseInfoServices BaseInfoServices

@{
    ViewData["Title"] = "Create";
}
<ul>
    @foreach (var city in BaseInfoServices.GetCities())
    {
    <li>@city</li>
    }
</ul>

    public class BaseInfoServices
    {
        public List<string> GetCities()
        {
            return new List<string>();
        }
    }

Need to be in advanceConfigureServices To add the service to the container.

1. fill in search data

View injection helps populate UI elements, such as drop-down lists. For example, a form that includes gender, state, and other user information. If the form is rendered in the standard MVC mode, the controller needs to request data access services for each set of options, and then populate each set of bound options into the model orViewBagMedium.

The other is to directly inject the service into the view to obtain these option data. This method minimizes the amount of controller code and moves the logic of constructing view elements to the view itself. controllerAction Just send the user data to a form.

2. rewrite service

In addition to injecting services, this technique can also be used to rewrite previously injected services on a page. For example, replace the defaultHTML Helper


@model MVCTest.Models.Operation
@using MVCTest.Services
@inject BaseInfoServices BaseInfoServices
@inject MyHtmlHelper Html


Use in view@Html The custom service will be called.

If you want to extend an existing service rather than replace it, you just need to use this technology and let the service inherit or encapsulate the existing implementation.

2、 Asp Net core MVC dependency injection controller

ASP.NET Core MVC Controllers should explicitly request their dependencies through constructors. In some cases, the operation of a single controller may require a service, and requests at the controller level may be meaningless. In this case, you can also use the service as a parameter of the action.

Dependency injection is aDependency Inversion Principle The techniques shown allow applications to be composed of loosely coupled modules.

1. constructor injection

  ASP.NET Core Built in constructor based dependency injection support extends to MVC controllers. By adding only one service type as a constructor parameter to the controller,ASP.NET Core We will try to resolve this type using the built-in service container. Services typically (but not always) use interface definitions. For example, if an application defines a service that retrieves time and then relies on injection rather than hard coding:

Define interfaces and Implementations:


namespace MVCTest.Services
{
    public interface IDateTime
    {
        DateTime Now { get; }
    }
    public class SystemDateTime: IDateTime
    {
        public DateTime Now
        {
            get { return DateTime.Now; }
        }
    }
}

stayConfigureServices Register service to container in:


services.AddTransient<IDateTime, SystemDateTime>();


Use in control:


    public class DateTimeController : Controller
    {
        private IDateTime _dateTime;
        public DateTimeController(IDateTime dateTime)
        {
            _dateTime = dateTime;
        }
        // GET: DateTime
        public ActionResult Index()
        {
            var serverTime = _dateTime.Now;
            if (serverTime.Hour < 12)
            {
                ViewData["Message"] = "Good Morning";
            }
            return View();
        }
}

  ASP.NET Core The built-in dependency injection supports that the type used to request the service can only have one constructor. If there is more than one constructor, an exception will be reported. Using a third-party implementation to replace the default dependency injection, you can support multiple constructors.

2. use fromservices operation injection

Sometimes, you do not need to service multiple operations on the controller. In this case, it makes sense to inject the service into the parameters of the operation method. adopt[FromServices] Tag parameters to implement:


  public ActionResult Index([FromServices] IDateTime _dateTime)
        {
            var serverTime = _dateTime.Now;
            if (serverTime.Hour < 12)
            {
                ViewData["Message"] = "Good Morning";
            }
            return View();
        }

3. access settings in the controller

Common patterns when accessing application settings or configuring settings in the controller. This access should use theConfiguration Access mode described in. In general, dependency injection should not be used from the controller to directly request settings, and the better way is to requestIOptions<T>Instance, t is the configuration type you need. For example:

To create an option class:


public class AppSettingOptions
    {
        public DefaultConnec ConnectionStrings { get; set; }
        public string AllowedHosts { get; set; }
    }

    public class DefaultConnec
    {
        public string DefaultConnection { get; set; }
    }

appsettings.json:


{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=.;Initial Catalog=Test;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  },
  "AllowedHosts": "*"
}

Configure the application to use the option model in theConfigureServices To add a configuration class to the service container:

public Startup(IConfiguration configuration,IHostingEnvironment env)
        {
            //Configuration = configuration;
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json",optional:true,reloadOnChange:true)
                //.AddJsonFile($"appsettings.{env.EnvironmentName}.json",optional:true)
                ;

            //Configure environment variables
            //builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.Configure<AppSettingOptions>(Configuration);
            //By coding
            services.Configure<AppSettingOptions>(options=>
            {
                options.AllowedHosts = "test";
            });
        }

An example is from appsettings.json Read settings, or add settings to your code.

Once you specify a configuration object of typeAppSettingOptions, and add it to the service containerController or operation method by requesting IOptions<AppSettingOptions>Instance of get it:


    public class HomeController : Controller
    {
        private readonly IOptions<AppSettingOptions> _options;
        public HomeController(IOptions<AppSettingOptions> options)
        {
            _options = options;
        }
}

Following the option mode allows setting and configuration to be separated from each other and ensures that the controller follows the separation of concerns because there is no need to know where to find the setting information. Because there is no static attachment or direct instantiation of the setting class in the controller class, it is easier for the controller to use unit tests.

This is aboutASP.NET Core MVCDependency injection view andControllerThat’s all for the article aboutASP.NET Core MVC Please search the previous articles of developeppaer or continue to browse the related articles below for the content of dependency injection. I hope you can support developeppaer in the future!

Recommended Today

Why is reids fast

1. What is redis? Redis is completely open source and complies with the BSD protocol. It is a high-performance key value database. Redis is also one of the most popular NoSQL databases at present. It contains a variety of data structures, supports network, is memory based, and has an optional key value pair storage database […]