ASP.NET Core MVC's dependency injection Controller

  ASP.NET Core MVC controller should request them through the constructor explicitly dependent relationship, in some cases, a single controller may be required to operate a service request on the controller level may not make sense. In this case, it can also serve as a parameter of the Action.

  Dependency injection is a technique as shown Dependency Inversion Principle, loosely coupled applications allow the modules composition.

1. constructor injection

  ASP.NET Core built based constructor dependency injection support extended to the MVC controller. By adding only a service type as a parameter to the constructor controller, ASP.NET Core Services Container will attempt to use the built-resolved this type. Service is usually (but not always) using an interface definition. For example, if an application defines a service search time, and instead of hard coding dependency injection:

  Define and implement interfaces:

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

  In ConfigureServices registered service to the container:

services.AddTransient<IDateTime, SystemDateTime>();

  In the control wherein:

    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 built-in support for dependency injection type of service request can only have one constructor, will be reported if more than one exception. Implemented using a third party to replace the default dependency injection, can be implemented to support multiple constructors.

 

2. Operation injection FromServices

  Sometimes, not necessary to provide service to a plurality of operations in the controller. In this case, the service parameters to the method of operating injection is significant. Achieved by [FromServices] markup parameters:

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

 

3. Access is provided in the controller

  In the controller to access the application settings or configure common setting mode. This access mode should be used to access described in the Configuration. Dependency injection generally should direct requests from the controller is provided, a better way is to request IOptions <T> instance, T is the desired type of configuration. E.g:

  Creating options categories:

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": "*"
}

  With the option to configure the application model, configuration class to add service containers ConfigureServices in:

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)
                ;

            //配置环境变量
            //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);
            //通过代码编写
            services.Configure<AppSettingOptions>(options=>
            {
                options.AllowedHosts = "test";
            });
        }

  Examples are provided reading from appsettings.json, may be added provided in the code.

  Once the requested type of the specified configuration object AppSettingOptions, and add it to the service container, it can be acquired by a method of operating a controller or <AppSettingOptions> Examples request IOptions:

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

  Follow mode option allows you to set up and configure separated from each other, and ensure that the controller follows the separation of concerns, because not need to know how to find information on where to set up. Since the controller is not a class instance or directly attached to a static class settings, thus making it easier to use the controller unit test.

 

 

 

 

Guess you like

Origin www.cnblogs.com/afei-24/p/11367425.html