NET Core 3.0 AutoFac replace the built-in DI's new posture

Original: NET Core 3.0 AutoFac replace the built-in DI's new posture

  .NET Core 3.0 and previous versions, replaced AutoFac services have a certain way of change, there have been some problems when trying to upgrade the project.

  In the original NET Core 2.1 times, AutoFac return a  IServiceProvider  parameter injection into ConfigureServices .NET Core service, a large mole is basically to do so.

  First, we need a rewrite  Autofac.Module  method, which will be for us  the Register  [Data Access Layer], and   Services  registered [logical layer] is.

Copy the code
public  class AutofacModuleRegister: Autofac.Module
    {
        // rewriting Autofac pipe Load method, where implanted register 
        protected  the override  void Load (ContainerBuilder Builder)
        {
            // must be the end of the Service 
            builder.RegisterAssemblyTypes (GetAssemblyByName ( " actual BlogService " )) the Where (A => a.Name.EndsWith (. " Service " )) AsImplementedInterfaces ().;
            builder.RegisterAssemblyTypes (GetAssemblyByName ( " BlogRepository " )) the Where (A => a.Name.EndsWith (. " the Repository " )) AsImplementedInterfaces ();.
             // single sign
             //   builder.RegisterType <PersonService> () Named <. IPersonService> (typeof (PersonService) .Name); 
        }
         ///  <Summary> 
        /// Get assembly according to assembly name
         ///  </ Summary> 
        ///  <param name = "the AssemblyName"> assembly name < / param> 
        public  static Assembly GetAssemblyByName (String AssemblyName)
        {
            return Assembly.Load(AssemblyName);
        }
    }
Copy the code

   Subsequently, ConfigureServices method of .NET Core return value into 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);
        }

  The above code, we call  ForRegisterAutoFac  method for our custom, which will replace the built-in DI with our strategy and AutoFac defined.

Copy the code
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);
        }
    }
Copy the code

   In the API layer, our dependency injection Service, so we .NET basic AutoFac Core2.1 realized.

Copy the code
[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());
        }
}
Copy the code

  For now we talk about the difference between .NET Core3.0 and previous versions. I'm all items and all dependencies into version 3.0, you now start, you'll find something unexpected.

 

 

What? You what? Get Sallee? Why do not work anymore le?

 

  After I read the official document, before we know ..NET Core 3.0  introduces the ability to have a strongly typed container configuration. It provides  ConfigureContainer  method, in which you can use to register things Autofac, without going through  ServiceCollection  to register things. so .... Well! How Core3.0 will be configured in .NET.

  First, we need to  Program.cs  modify the service factory, built a  ServiceProviderFactory  , we will want to designate as:  AutofacServiceProviderFactory  .

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

  现在需要在 Startup.cs 中添加方法 ConfigureContainer ,并添加以下代码。

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

Then you're done, start - never a problem.

 Github Address: https://github.com/zaranetCore/Blog.DDD.Solucation

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/12052138.html