catalogue
preface:
Remember in the last articleASP. Net core dependency injection detailsFinally, I mentioned how to deal with more and more services. This article will bring solutions. This article is a continuation of the previous article. For conceptual aspects, please refer to the previous article.
1、 IOC framework
Let’s talk about the common IOC framework first.
Autofac:
at presentnet
I use a lot of frameworks. Many big guys’ projects prefer the framework.
Ninject:
It is rarely used. I have seen it in a very early article.
Unity:
It’s quite common. It’s useful in many places,
Core: Core
It is quite convenient when the business logic is not too complicated.
2、 IOC Autofac
Autofac
yes.NET
The most popularIOC
One of the frames, legend is the fastest one.
advantage:
- It is closely related to c\
Autofac
use. - Lower learning curve, learning it is very simple, as long as you understand
IoC
And di and when they need to be used. XML.Json
Configuration support.- Automatic assembly.
- And
Asp.Net MVC
integrate. - Microsoft
Orchad
Open source programs useAutofac
From the source code, we can see its convenience and power.
Mostly speakingAutofac
Framework articles will mention the above advantages, which shows the excellence of the framework.
3、 Use of built-in Di in net core
1. first create a ASP.Net Core Web Api
The project (selected.Net 5.0) is as follows as a whole. The red part is used by the built-in Di in the core.
2. create a new class library project and add an interface file and a class file respectively.
Interface:
public interface ISayHelloService
{
string SayHello(string name);
}
Class:
public class EnglishSayHelloService : ISayHelloService
{
public string SayHello(string name)
{
return $"Hello,{name}!";
}
}
3. inStartup
InsideConfigureServices
Method injection.
services.AddScoped<ISayHelloService, EnglishSayHelloService>();
4. then use the service just injected in the controller.
[Route("api/[controller]/[action]")]
[ApiController]
public class HelloController : ControllerBase
{
public readonly ISayHelloService sayHelloService;
public HelloController(ISayHelloService sayHelloService)
{
this.sayHelloService = sayHelloService;
}
[HttpGet]
public string CoreDI()
{
return sayHelloService.SayHello("CoreDI");
}
}
be careful:When a 404 error occurs in a route access address, it may be a routing problem. The route can be modified at [route (“api/[controller]/[action])] according to your actual needs.
5. access test.
The interface test software used here isPostman
The API test is very convenient. You can search it on the Internet. If you can’t find it, you can contact me.
4、 Autofac use
1. create a newASP.Net Core Web Api
The project (selected.Net 5.0) is used to distinguish the Di of the previous core.
2. quotationAutofac
Look at the download volume. It’s still very wow
3. inProgram
Use inAutofac
To implement dependency injection
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
4.Add a method to the startup class:ConfigureContainer
, inject our previous service.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
//Inject here
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<EnglishSayHelloService>().As<ISayHelloService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
5. there is basically no need to change the controller here.
[Route("api/[controller]/[action]")]
[ApiController]
public class HelloController : ControllerBase
{
public readonly ISayHelloService sayHelloService;
public HelloController(ISayHelloService sayHelloService)
{
this.sayHelloService = sayHelloService;
}
[HttpGet]
public string CoreDI()
{
return sayHelloService.SayHello("AutofacDI");
}
}
6. run the project and continue to test the interface with postman.
All right aboutAutofac
The basic use of is basically finished. Is it still very simple.
5、 Batch injection
A few simple services are acceptable. When there are dozens or even hundreds of services, it is terrible to think about them. We have to talk about batch injection, and the advantages of Autofac are reflected.
1. add an interface and a class to the service.
Interface:
public interface IUseAutofacService
{
string UseAutofac(string name);
}
Class:
public class UseAutofacService : IUseAutofacService
{
public string UseAutofac(string name)
{
Return $"{name} batch injection test!";
}
}
2. go back to our previous startup class and modify the method:ConfigureContainer
。
public void ConfigureContainer(ContainerBuilder builder)
{
//builder.RegisterType<EnglishSayHelloService>().As<ISayHelloService>();
//Service project assembly
Assembly service = Assembly.Load("Autofac.Service");
//Service interface project assembly
Assembly iservice = Assembly.Load("Autofac.Service");
builder.RegisterAssemblyTypes(service, iservice).Where(n => n.FullName.EndsWith("Service") && !n.IsAbstract)
.InstancePerLifetimeScope().AsImplementedInterfaces();
}
be careful:If the service to be injected does not IXXXService
Interface, then builder.RegisterAssemblyTypes
You just need to pass an assembly. If the service and interface are in the same project, it is also necessary to pass two assemblies.
3. next, slightly modify the controller just now.
[Route("api/[controller]/[action]")]
[ApiController]
public class HelloController : ControllerBase
{
public readonly ISayHelloService sayHelloService;
public readonly IUseAutofacService useAutofacService;
public HelloController(ISayHelloService _sayHelloService, IUseAutofacService _useAutofacService)
{
this.sayHelloService = _sayHelloService;
this.useAutofacService = _useAutofacService;
}
[HttpGet]
public string AutofacDI()
{
return sayHelloService.SayHello("AutofacDI");
}
public string BathAutofacDI()
{
var name = sayHelloService.SayHello("AutofacDI");
return useAutofacService.UseAutofac(name);
}
}
4. usePostman
Test the injection.
This is about asp This is the end of the article on the use of the. Net core dependency injection framework. More related asp Net core dependency injection framework content, please search the previous articles of developeppaer or continue to browse the related articles below. I hope you will support developeppaer in the future!