ASP.NET Core Series: Dependency Injection

1. Inversion of Control (IoC)

  Inversion of control (Inversion of Control, IoC), one design principles of object-oriented programming, to reduce the degree of coupling between the tags.

1.1 Dependency Inversion

  Dependencies Principle:

  (1) high-level modules should not depend on low-level modules, which should depend on the abstract.

  (2) should not rely on particular abstract, it should depend on the specific abstraction.

1.2 Dependency injection

  Dependency injection: the dependent portion (or code is not frequently change controllable coupling portion) becomes a member of the abstract (class, an abstract class or interface), and an example of the specific required to rely on a flexible injection, to achieve controlled trans transfer effect, thereby achieving decouple code.

  Dependency injection is inverted control a specific implementation.

  C # common dependency injection:

  (1) by the constructor dependency injection

  (2) Dependency injection through property accessors

  (3) dependency injection through the interface

  (4) by reflection, it may be implementation-dependent characteristics of injection

2. ASP.NET Core comes with dependency injection

  Dependency injection installation package:

Install-Package Microsoft.Extensions.DependencyInjection

  ASP.NET Core provides a built-in service containers IServiceProvider, the configuration dependent Startup.ConfigureServices injection process.

  ASP.NET Core Services lifetime registration:

  (1) AddTransient: temporary survival, to create each time a request from the service container.

  (2) AddScoped: Scope survival, each client request (connection) once created.

  (3) AddSingleton: a single instance of a lifetime service, created when the first request, every subsequent request to use the same instance.

  Example:

public interface ILogRepository
{
    int Insert(Log log);
}
ILogRepository
public class LogRepository : ILogRepository
{
    public int Insert(Log log)
    {
        using (var context = new PortalContext())
        {
            context.Logs.Add(new Log
            {
                UserName = log.UserName,
                Content = log.Content,
                CreateTime = DateTime.Now
            });

            return context.SaveChanges();
        }
    }
}
LogRepository

  Startup.cs

using Microsoft.Extensions.DependencyInjection;

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ILogRepository, LogRepository>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

  LogController.cs

[Route("api/[controller]")]
[ApiController]
public class LogController : ControllerBase
{
    private readonly ILogRepository _logRepository;

    public LogController(ILogRepository logRepository)
    {
        _logRepository = logRepository;
    }

    [HttpPost]
    public void Post([FromBody] Log value)
    {
        _logRepository.Insert(value);
    }
}

3. ASP.NET Core Autofac use dependency injection

  Add installation package:

Install-Package Autofac.Extensions.DependencyInjection

  Startup.cs:

using Autofac;
using Autofac.Extensions.DependencyInjection;

// 使用第三方容器,Startup.ConfigureServices 必须返回 IServiceProvider
public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // Autofac
    var builder = new ContainerBuilder();
    builder.RegisterType<LogRepository>().As<ILogRepository>();
    builder.Populate(services);
    var container = builder.Build();
    return new AutofacServiceProvider(container);
}

Guess you like

Origin www.cnblogs.com/libingql/p/11417512.html