Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is IOC in asp.net core

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "what is IOC in asp.net core". In daily operation, I believe many people have doubts about what is IOC in asp.net core. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubt of "what is IOC in asp.net core?" Next, please follow the editor to study!

1. IOC and DI

First of all, let's explain a few concepts, the full name of IOC is Inversion of Control, which translates as control inversion, which is a design principle of object-oriented programming to reduce the coupling between code. The so-called control inversion simply means handing over the initialization of properties or other parameters in the class to other parties, rather than directly using the constructor.

Public class Demo1

{

}

Public class Demo2

{

Public Demo1 demo

}

For the simple sample code above, an instance of Demo1 is held in the Demo2 class. If we follow the previous situation, we will assign a value to demo in the following ways:

/ / method one

Public Demo1 demo = new Demo1 ()

/ / method 2

Public Demo2 ()

{

Demo = new Demo1 ()

}

At this point, if the Demo1 becomes like this:

Public class Demo1

{

Public Demo1 (Demo3 demo3)

{

/ / hide

}

}

Public class Demo3

{

}

So, if Demo2 does not hold an instance object of Demo3, you need to construct an additional Demo3 when you create the Demo1. If Demo3 needs to hold an object of another class, then one more object needs to be created in Demo2. In the end, you will find yourself in a structural "hell" (a word I coined to mean that you have to construct a lot of other types of objects for one object).

In fact, Demo2 doesn't care about how the instance object of Demo1 is obtained, or even whether it is a subclass or interface implementation class of Demo1. I used the class in the example, but here I can synchronously replace it with Interface. After that, when Demo2 calls Demo1, it also needs to know that Demo1 has an implementation class, as well as information about the implementation class.

In order to solve this problem, some clever programmers have proposed to leave the process of object creation to a third party instead of calling the class to create it. Therefore, the above code becomes:

Public class Demo2

{

Public Demo1 Demo {get;set;}

Public Demo2 (Demo1 demo)

{

Demo = demo

}

}

Doesn't seem to have changed? For Demo2, Demo2 is no longer responsible for the creation of Demo1, this step is left to the caller of Demo2 to create, and Demo2 is freed from the hassle of maintaining the Demo1 object.

But in fact, the problem of constructing hell has not been solved, but this step has been moved back through the design of IOC. At this time, the great gods thought that it would be better to develop a framework for these entity objects. So there are a lot of IOC frameworks: AutoFac, Sping.net, Unity and so on.

Speaking of IOC, I have to mention DI (Dependency Injection) dependency injection. The so-called dependency injection is that the corresponding instance of the attribute is assigned by a third party through the constructor or the use of the attribute. This is how it is written in the sample code of the final Demo2.

In the early days, IOC and DI referred to a technology, but later began to determine that it was a different description. IOC describes a design pattern, while DI is a behavior.

two。 Use the default IOC for asp.net core

In the previous ASP.NET framework, Microsoft did not provide default IOC support. In the latest asp.net core, Microsoft provides a set of IOC support in the namespace:

Microsoft.Extensions.DependencyInjection

You can refer to it in the code.

It is mainly realized through the following groups of methods:

Public static IServiceCollection AddScoped (this IServiceCollection services) where TService: class

Public static IServiceCollection AddSingleton (this IServiceCollection services) where TService: class

Public static IServiceCollection AddTransient (this IServiceCollection services) where TService: class

Only one overloaded version of these three sets of methods is listed here.

These three sets of methods represent three lifecycles:

AddScored indicates that the life cycle of the object is the entire Request request

AddTransient represents a lightweight, stateless service created each time a request is made from a service container

AddSingleton indicates that the object is obtained after the first request from the service container and will not be initialized again

There is only one version of each set of methods, but in fact each method has the following versions:

Public static IServiceCollection AddXXX (this IServiceCollection services) where TService: class

Public static IServiceCollection AddXXX (this IServiceCollection services, Type serviceType, Type implementationType)

Public static IServiceCollection AddXXX (this IServiceCollection services, Type serviceType, Func implementationFactory)

Public static IServiceCollection AddXXX (this IServiceCollection services)

Where TService: class

Where TImplementation: class, TService

Public static IServiceCollection AddXXX (this IServiceCollection services, Type serviceType)

Public static IServiceCollection AddXXX (this IServiceCollection services, Func implementationFactory) where TService: class

Public static IServiceCollection AddXXX (this IServiceCollection services, Func implementationFactory)

Where TService: class

Where TImplementation: class, TService

Where: implementationFactory represents a factory method that implements TService/TImplementation through a Provider. When the method specifies a generic type, the type information to be injected is automatically obtained based on the generic parameter, and if the generic type is not used, the parameter type must be passed in manually.

If asp.net core uses dependency injection, you need to set it in the Startup method. For more information, please see the following:

Public void ConfigureServices (IServiceCollection services)

{

/ / other codes are omitted

Services.AddScoped ()

}

Asp.net core provides different IOC support for DbContext, AddDbContext:

Public static IServiceCollection AddDbContext (

This IServiceCollection serviceCollection

Action optionsAction = null

ServiceLifetime contextLifetime = ServiceLifetime.Scoped

ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)

Where TContext: DbContext

The method of use is as follows:

Services.AddDbContext ()

3. AutoFac usage

In theory, asp.net core's IOC is good enough, but still forgive my greed. If there are two or three hundred business classes I need to set up, I'd rather not use IOC. Because that configuration is an extremely painful process. However, the good news is that AutoFac can save me from this part of the trouble.

Here is a brief introduction to how to use AutoFac as IOC management:

Cd Web # change directory to Web project

Dotnet package add Autofac.Extensions.DependencyInjection # add a reference to AutoFac

Because asp.net core version 3 has changed some logic, the way AutoFac is referenced has changed, and the content of the previous version is not introduced now, focusing on 3. To use AutoFac, you need to set the following code in the Program class:

Public static IHostBuilder CreateHostBuilder (string [] args) = >

Host.CreateDefaultBuilder (args)

.UseServiceProviderFactory (new AutofacServiceProviderFactory ()) / / add this line of code

.ConfigureWebHostDefaults (webBuilder = >

{

WebBuilder.UseStartup ()

});

A Service that enables AutoFac in the Program class provides the factory class. Then add the following methods to the Startup class:

Public void ConfigureContainer (ContainerBuilder builder)

{

Builder.RegisterType () .As ()

.WithParameter ("connectStr", "Data Source=./demo.db")

.InstancePerLifetimeScope ()

Builder.RegisterAssemblyTypes (Assembly.Load ("Web"))

.Where (t = > t.BaseType.FullName.Contains ("Filter"))

.AsSelf ()

Builder.RegisterAssemblyTypes (Assembly.Load ("Domain")

Assembly.Load ("Domain.Implements"), Assembly.Load ("Service"), Assembly.Load ("Service.Implements"))

.AsSelf ()

.AsImplementedInterfaces ()

.InstancePerLifetimeScope ()

.PropertiesAutoexamples ()

}

Modify:

Public void ConfigureServices (IServiceCollection services)

{

Services.AddControllersWithViews (options = >

{

Options.Filters.Add ()

}). AddControllersAsServices (); / / this line is added

/ / omit other

At this point, the study of "what is IOC in asp.net core" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report