Net core 3.0 autoface new pose sharing with built-in Di replacement

Time:2020-5-11

. net core 3.0 is different from the previous version. There are some changes in the way of replacing Autofac services, and some problems arise when trying to upgrade the project.

Originally, in net core 2.1, Autofac returned an iserviceprovider parameter and injected it into the configureservices. Net core service. This is what the basic big mole does.

First of all, we need a method to rewrite the autofac.module, which will be used to register our register (data access layer) and services (logical layer).

public class AutofacModuleRegister : Autofac.Module
 {
  //Override the Autofac pipeline load method to register the injection here
  protected override void Load(ContainerBuilder builder)
  {
   //Must be end of service
   builder.RegisterAssemblyTypes(GetAssemblyByName("BlogService")).Where(a => a.Name.EndsWith("Service")).AsImplementedInterfaces();
   builder.RegisterAssemblyTypes(GetAssemblyByName("BlogRepository")).Where(a => a.Name.EndsWith("Repository")).AsImplementedInterfaces();
   //Single sign up
   // builder.RegisterType<PersonService>().Named<IPersonService>(typeof(PersonService).Name);
  }
  /// <summary>
  ///Get assembly from assembly name
  /// </summary>
  ///< param name = "assemblyname" > assembly name < / param >
  public static Assembly GetAssemblyByName(String AssemblyName)
  {
   return Assembly.Load(AssemblyName);
  }
 }

Then change the return value of the. Net core’s configureservices method to iserviceprovider, which will be used to inject your service.


 public IServiceProvider ConfigureServices(IServiceCollection services)
  {
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
   return Blog.AutoFacModule.Solucation.AutoFac.Provider.RegisterAutofac.ForRegisterAutofac(services);
  }

In the above code, we call our custom method forregisterautofac, which replaces the built-in Di with our defined policy and Autofac


public static class RegisterAutofac
 {
  public static IServiceProvider ForRegisterAutofac(IServiceCollection services)
  {
   var builder = new ContainerBuilder();
   builder.Populate(services);
   builder.RegisterModule<Blog.AutoFacModule.Solucation.AutoFac.Register.AutofacModuleRegister>();
   var container = builder.Build(); 
   return new AutofacServiceProvider(container);
  }
 }

In the API layer, we rely on injection services, so that our. Net core 2.1 basic autoface is implemented.


[Route("api/[controller]")]
 [ApiController]
 public class ValuesController : ControllerBase
 {
  private IPersonService _personService;
  public ValuesController(IPersonService personService)
  {
   _personService = personService;
  }
  // GET api/values
  [HttpGet]
  public ActionResult<string> Get()
  {
   return Newtonsoft.Json.JsonConvert.SerializeObject(_personService.people());
  }
}

Now let’s talk about the difference between. Net core 3.0 and previous versions. I’ll change all the projects and dependencies to version 3.0, start now, and you’ll find something unexpected.

What? What do you say? Do you feel tired? Why doesn’t it work?

After reading the official documents, we know that.. net core 3.0 has introduced the function of strong type container configuration. It provides the configurecontainer method, where you can register things using Autofac instead of servicecollection. So… OK! How will be configured in. Net core 3.0.

First of all, we need to modify the service factory in program.cs. The built-in is serviceproviderfactory. We will specify it as: autofacserviceproviderfactory.


public static IHostBuilder CreateHostBuilder(string[] args) =>
   Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
     webBuilder.UseStartup<Startup>();
    })
  .UseServiceProviderFactory(new AutofacServiceProviderFactory());

Now you need to add the method configurecontainer in startup.cs and add the following code.

public void ConfigureContainer(ContainerBuilder builder)
  {
   //Add dependency injection relationship
   builder.RegisterModule(new Blog.AutoFacModule.Solucation.AutoFac.Register.AutofacModuleRegister());
   var controllerBaseType = typeof(ControllerBase);
   //Using dependency injection in the controller
   builder.RegisterAssemblyTypes(typeof(Program).Assembly)
    .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
    .PropertiesAutowired();
  }

And then it’s done. There’s no problem starting it.

GitHub address: https://github.com/zaranetcore/blog.ddd.solution

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer.