• Autofac asp.netcore 几种容器注入方法


    方法1 netcore3.0+

     public class Startup
        {
            public void Configure(IApplicationBuilder app)
            {
                app.UseRouting();
                app.UseEndpoints(builder => builder.MapControllers());
              
            }
    
            public void ConfigureContainer(ContainerBuilder builder)
            {
                // Add any Autofac modules or registrations.
                // This is called AFTER ConfigureServices so things you
                // register here OVERRIDE things registered in ConfigureServices.
                //
                // You must have the call to `UseServiceProviderFactory(new AutofacServiceProviderFactory())`
                // when building the host or this won't be called.
                builder.RegisterModule(new AutofacModule());
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                // Use extensions from libraries to register services in the
                // collection. These will be automatically added to the
                // Autofac container.
                services.AddControllers();
            }
        }
    
     public static async Task Main(string[] args)
            {
                // The `UseServiceProviderFactory(new AutofacServiceProviderFactory())` call here allows for
                // ConfigureContainer to be supported in Startup with
                // a strongly-typed ContainerBuilder. If you don't
                // have the call to AddAutofac here, you won't get
                // ConfigureContainer support. This also automatically
                // calls Populate to put services you register during
                // ConfigureServices into Autofac.
                var host = Host.CreateDefaultBuilder(args)
                    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
                    .ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.UseStartup<Startup>())
                    .Build();
    
                await host.RunAsync();
            }
    
       public class AutofacModule : Module
        {
            protected override void Load(ContainerBuilder builder)
            {
                // The generic ILogger<TCategoryName> service was added to the ServiceCollection by ASP.NET Core.
                // It was then registered with Autofac using the Populate method. All of this starts
                // with the `UseServiceProviderFactory(new AutofacServiceProviderFactory())` that happens in Program and registers Autofac
                // as the service provider.
                builder.Register(c => new ValuesService(c.Resolve<ILogger<ValuesService>>()))
                    .As<IValuesService>()
                    .InstancePerLifetimeScope();
            }
        }
    

     方法2 netcore2.0+

     public class Startup
        {
            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddEnvironmentVariables();
                this.Configuration = builder.Build();
            }
    
            public IConfigurationRoot Configuration { get; private set; }
    
            public void Configure(IApplicationBuilder app)
            {
                app.UseMvc();
            }
    
            public void ConfigureContainer(ContainerBuilder builder)
            {
                // Add any Autofac modules or registrations.
                // This is called AFTER ConfigureServices so things you
                // register here OVERRIDE things registered in ConfigureServices.
                //
                // You must have the call to AddAutofac in the Program.Main
                // method or this won't be called.
                builder.RegisterModule(new AutofacModule());
            }
    
            public void ConfigureServices(IServiceCollection services)
            {
                // Use extensions from libraries to register services in the
                // collection. These will be automatically added to the
                // Autofac container.
                //
                // Note if you have this method return an IServiceProvider
                // then ConfigureContainer will not be called.
                services.AddMvc();
            }
        }
    
        public static void Main(string[] args)
            {
                // The ConfigureServices call here allows for
                // ConfigureContainer to be supported in Startup with
                // a strongly-typed ContainerBuilder. If you don't
                // have the call to AddAutofac here, you won't get
                // ConfigureContainer support. This also automatically
                // calls Populate to put services you register during
                // ConfigureServices into Autofac.
                var host = WebHost.CreateDefaultBuilder(args)
                    .ConfigureServices(services => services.AddAutofac())
                    .UseStartup<Startup>()
                    .Build();
    
                host.Run();
            }
    
        public class AutofacModule : Module
        {
            protected override void Load(ContainerBuilder builder)
            {
                // The generic ILogger<TCategoryName> service was added to the ServiceCollection by ASP.NET Core.
                // It was then registered with Autofac using the Populate method. All of this starts
                // with the services.AddAutofac() that happens in Program and registers Autofac
                // as the service provider.
                builder.Register(c => new ValuesService(c.Resolve<ILogger<ValuesService>>()))
                    .As<IValuesService>()
                    .InstancePerLifetimeScope();
            }
        } 

    策略容器  

     相当于一个注册组,根据设定的参数 1,2,null 实现 1,2 默认策略

    using System;
    using Autofac;
    using Autofac.Multitenant;
    
    namespace MultitenantExample.ConsoleApplication
    {
        /// <summary>
        /// Demonstration console application illustrating multitenant dependency injection.
        /// </summary>
        /// <remarks>
        /// <para>
        /// While there is not much of a use case for a console application to be
        /// multitenant, what this illustrates is that non-ASP.NET, non-WCF applications
        /// can also be multitenant. Windows services, for example, could make use
        /// of multitenancy.
        /// </para>
        /// </remarks>
        public class Program
        {
            /// <summary>
            /// The container from which dependencies will be resolved.
            /// </summary>
            private static IContainer _container;
    
            /// <summary>
            /// Strategy used for identifying the current tenant with multitenant DI.
            /// </summary>
            private static ManualTenantIdentificationStrategy _tenantIdentifier;
    
            /// <summary>
            /// Demo program entry point.
            /// </summary>
            public static void Main()
            {
                // Initialize the tenant identification strategy.
                _tenantIdentifier = new ManualTenantIdentificationStrategy();
    
                // Set the application container to the multitenant container.
                _container = ConfigureDependencies();
    
                // Explain what you're looking at.
                WriteInstructions();
    
                // Start listening for input.
                ListenForInput();
            }
    
            /// <summary>
            /// Configures the multitenant dependency container.
            /// </summary>
            private static IContainer ConfigureDependencies()
            {
                // Register default dependencies in the application container.
                var builder = new ContainerBuilder();
                builder.RegisterType<Consumer>().As<IDependencyConsumer>().InstancePerDependency();
                builder.RegisterType<BaseDependency>().As<IDependency>().SingleInstance();
                var appContainer = builder.Build();
    
                // Create the multitenant container.
                var mtc = new MultitenantContainer(_tenantIdentifier, appContainer);
    
                // Configure overrides for tenant 1. Tenant 1 registers their dependencies
                // as instance-per-dependency.
                mtc.ConfigureTenant('1', b => b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency());
    
                // Configure overrides for tenant 2. Tenant 2 registers their dependencies
                // as singletons.
                mtc.ConfigureTenant('2', b => b.RegisterType<Tenant2Dependency>().As<IDependency>().SingleInstance());
    
                // Configure overrides for the default tenant. That means the default
                // tenant will have some different dependencies than other unconfigured
                // tenants.
                mtc.ConfigureTenant(null, b => b.RegisterType<DefaultTenantDependency>().As<IDependency>().SingleInstance());
    
                return mtc;
            }
    
            /// <summary>
            /// Loops and listens for input until the user quits.
            /// </summary>
            private static void ListenForInput()
            {
                ConsoleKeyInfo input;
                do
                {
                    Console.Write("Select a tenant (1-9, 0=default) or 'q' to quit: ");
                    input = Console.ReadKey();
                    Console.WriteLine();
    
                    if (input.KeyChar >= 48 && input.KeyChar <= 57)
                    {
                        // Set the "contextual" tenant ID based on the input, then
                        // put it to the test.
                        _tenantIdentifier.CurrentTenantId = input.KeyChar;
                        ResolveDependencyAndWriteInfo();
                    }
                    else if (input.Key != ConsoleKey.Q)
                    {
                        Console.WriteLine("Invalid key pressed.");
                    }
                } while (input.Key != ConsoleKey.Q);
            }
    
            /// <summary>
            /// Resolves the dependency from the container and displays some information
            /// about it.
            /// </summary>
            private static void ResolveDependencyAndWriteInfo()
            {
                var consumer = _container.Resolve<IDependencyConsumer>();
                Console.WriteLine("Tenant ID:       {0}", _tenantIdentifier.CurrentTenantId);
                Console.WriteLine("Dependency Type: {0}", consumer.Dependency.GetType().Name);
                Console.WriteLine("Instance ID:     {0}", consumer.Dependency.InstanceId);
                Console.WriteLine();
            }
    
            /// <summary>
            /// Writes the application instructions to the screen.
            /// </summary>
            private static void WriteInstructions()
            {
                Console.WriteLine("Multitenant Example: Console Application");
                Console.WriteLine("----------------------------------------");
                Console.WriteLine("Select a tenant ID (1 - 9) to see the dependencies that get resolved for that tenant. You will see the dependency type as well as the instance ID so you can verify the proper type and lifetime scope registration is being used.");
                Console.WriteLine();
                Console.WriteLine("* Tenant 1 has an override registered as InstancePerDependency.");
                Console.WriteLine("* Tenant 2 has an override registered as SingleInstance.");
                Console.WriteLine("* The default tenant has an override registered as SingleInstance.");
                Console.WriteLine("* Tenants that don't have overrides fall back to the application/base singleton.");
                Console.WriteLine();
            }
        }
    }
    

      

  • 相关阅读:
    SprimgMVC学习笔记(五)—— Controller方法返回值
    SprimgMVC学习笔记(四)—— @RequestMapping
    SprimgMVC学习笔记(三)—— 参数绑定
    SprimgMVC学习笔记(二)—— 整合Mybatis
    SprimgMVC学习笔记(一)—— SpringMVC入门
    mysql
    进程与线程
    xml
    生成器
    并发多线程
  • 原文地址:https://www.cnblogs.com/ms_senda/p/12613135.html
Copyright © 2020-2023  润新知