Asp.NetCoreAutofac framework uses actual combat, Dependency injection
Autofac DI .NET Autofac Autofac Autofac DLL Autofac XML Autofac Autofac DI Autofac TransientScopedSingletonAOP Autofac AOP Castle DynamicProxy Autofac DI Autofac ContainerBuilderIContainer { // ContainerBuilder builder = new ContainerBuilder(); builder
Autofac DI .NET Autofac
Autofac
Autofac DLL
Autofac XML
Autofac Autofac DI
Autofac TransientScopedSingleton
AOP Autofac AOP Castle DynamicProxy
Autofac DI
Autofac ContainerBuilderIContainer
{ // ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DogService>().As<IDogService>(); builder.RegisterType<PersonService>().As<IPersonService>(); IContainer container = builder.Build(); var p = container.Resolve<IPersonService>(); p.Say(); p.PlayerWithDog(); }
RegisterTypeIDogServiceIPersonServicePersionServiceIDogService
{ ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<PigService>().As<IPigService>(); builder.RegisterType<CatService>().As<ICatService>(); builder.RegisterType<DogService>().As<IDogService>(); builder.RegisterType<PersonService>().As<IPersonService>(); IContainer container = builder.Build(); var p = container.Resolve<IPersonService>(); p.Say(); p.PlayerWithDog();}
RegisterTypeIDogServiceICatServiceIPigService
{ ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DogService>().As<IDogService>(); builder.RegisterType<CatService>().As<ICatService>(); //UsingConstructor builder.RegisterType<PersonService>().As<IPersonService>().UsingConstructor(typeof(IDogService), typeof(ICatService)); IContainer container = builder.Build(); var p = container.Resolve<IPersonService>(); p.Say(); p.PlayerWithDog(); p.PlayerWithCat(); }
RegisterTypeIDogServiceICatServiceUsingConstructor
{ ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DogService>().As<IDogService>(); builder.RegisterType<CatService>().As<ICatService>(); builder.RegisterType<PigService>().As<IPigService>(); //PropertiesAutowired AnimalService builder.RegisterType<AnimalService>().As<IAnimalService>().PropertiesAutowired(); IContainer container = builder.Build(); var p = container.Resolve<IAnimalService>(); p.Say(); }
PropertiesAutowired AnimalService
{ // ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DogService>().As<IDogService>(); builder.RegisterType<CatService>().As<ICatService>(); builder.RegisterType<PigService>().As<IPigService>(); //PropertiesAutowired AnimalService2 builder.RegisterType<AnimalService2>().As<IAnimalService>().PropertiesAutowired(new IoctAttributeSelector()); IContainer container = builder.Build(); var p = container.Resolve<IAnimalService>(); p.Say(); }
PropertiesAutowirednew IoctAttributeSelector() AnimalService2
{ // ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DogService>().As<IDogService>(); builder.RegisterType<CatService>().As<ICatService>(); builder.RegisterType<PigService>().As<IPigService>(); builder.RegisterType<AnimalService>().As<IAnimalService>().OnActivated(Activator => { var dogService = Activator.Context.Resolve<IDogService>(); var catService = Activator.Context.Resolve<ICatService>(); var pigService = Activator.Context.Resolve<IPigService>(); Activator.Instance.Play(catService, dogService, pigService); }); IContainer container = builder.Build(); //IAnimalServicePlay var p = container.Resolve<IAnimalService>(); }
AnimalServicePlay
key
{ // key ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<DogService>().Keyed<ISkillService>("dog"); builder.RegisterType<CatService>().Keyed<ISkillService>("cat"); builder.RegisterType<PigService>().Keyed<ISkillService>("pig"); IContainer container = builder.Build(); // var dog = container.ResolveKeyed<ISkillService>("dog"); dog.ReleaseSkills(); // var cat = container.ResolveKeyed<ISkillService>("cat"); cat.ReleaseSkills(); // var pig = container.ResolveKeyed<ISkillService>("pig"); pig.ReleaseSkills();}
key
{ // ContainerBuilder builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(GenericAService<>)).As(typeof(IGenericAService<>)); builder.RegisterGeneric(typeof(GenericBService<,>)).As(typeof(IGenericBService<,>)); IContainer container = builder.Build(); var p = container.Resolve<IGenericAService<Dog>>(); var name1 = p.GetFullName(); var p2 = container.Resolve<IGenericBService<Dog, Cat>>(); var name2 = p2.GetFullName(); }
1
{ // ContainerBuilder builder = new ContainerBuilder(); Assembly assemblyInterface = Assembly.LoadFrom("ITestLibraryService.dll"); Assembly assemblyService = Assembly.LoadFrom("TestLibraryService.dll"); builder.RegisterAssemblyTypes(assemblyInterface, assemblyService).AsImplementedInterfaces(); IContainer container = builder.Build(); //PersonService var p = container.Resolve<IPersonService>(); p.PlayerWithDog(); p.PlayerWithCat(); p.PlayerWithPig(); }
AutoFac
2
{ // ContainerBuilder builder = new ContainerBuilder(); Assembly iService = Assembly.Load("ITestLibraryService"); Assembly service = Assembly.Load("TestLibraryService"); builder.RegisterAssemblyTypes(iService, service).Where(p => p.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope(); IContainer container = builder.Build(); var p = container.Resolve<IPersonService>(); p.PlayerWithDog(); p.PlayerWithCat(); p.PlayerWithPig();}
Service
WebApiAutofac
Nuget
<ItemGroup> <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="8.0.0" /> <PackageReference Include="Autofac.Extras.DynamicProxy" Version="7.1.0" /> <PackageReference Include="Castle.Core" Version="5.1.1" /></ItemGroup>
Program
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>()); builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>((builder) => { var controllersTypesInAssembly = typeof(Program).Assembly.GetExportedTypes() .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray(); builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(); // builder.RegisterGeneric(typeof(GenericAService<>)).As(typeof(IGenericAService<>)); builder.RegisterGeneric(typeof(GenericBService<,>)).As(typeof(IGenericBService<,>)); Assembly iService = Assembly.Load("ITestLibraryService"); Assembly service = Assembly.Load("TestLibraryService"); builder.RegisterAssemblyTypes(iService, service).Where(p => p.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope(); });
InstancePerDependency
builder.RegisterType<TestAService>().As<ITestAService>().InstancePerDependency();
InstancePerLifetimeScope()
builder.RegisterType<TestBService>().As<ITestBService>().InstancePerLifetimeScope();
InstancePerMatchingLifetimeScope("name") * name*
builder.RegisterType<TestDService>().As<ITestDService>().InstancePerMatchingLifetimeScope("myscope");
SingleInstance
builder.RegisterType<TestCService>().As<ITestCService>().SingleInstance();
AOP Castle DynamicProxy
using Autofac;using Autofac.Extensions.DependencyInjection;using Autofac.Extras.DynamicProxy;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Controllers;using Microsoft.Extensions.DependencyInjection.Extensions;namespace CastleDynamicProxyDemo{ public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // ... builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>()); builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>((builder) => { var controllersTypesInAssembly = typeof(Program).Assembly.GetExportedTypes() .Where(type => typeof(ControllerBase).IsAssignableFrom(type)).ToArray(); builder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired(); // builder.RegisterType<SimpleService>().As<ISimpleService>() .EnableInterfaceInterceptors().InterceptedBy(typeof(LogInvocationInterceptor)); builder.RegisterType<LogInvocationInterceptor>().SingleInstance(); }); var app = builder.Build(); //..... app.Run(); } }}
using Castle.DynamicProxy;namespace CastleDynamicProxyDemo{ public class LogInvocationInterceptor : IInterceptor { private readonly ILogger<LogInvocationInterceptor> _logger; public LogInvocationInterceptor(ILogger<LogInvocationInterceptor> logger) { _logger = logger; } public void Intercept(IInvocation invocation) { PrevProceed(invocation); Proceed(invocation); AfterProceed(invocation); } /// <summary> /// /// </summary> /// <param name="invocation"></param> protected virtual void Proceed(IInvocation invocation) { //, invocation.Proceed(); } /// <summary> /// /// </summary> /// <param name="invocation"></param> protected virtual void PrevProceed(IInvocation invocation) { _logger.LogInformation(invocation.Method.Name); _logger.LogInformation($"{invocation.Arguments}"); } /// <summary> /// /// </summary> /// <param name="invocation"></param> protected virtual void AfterProceed(IInvocation invocation) { _logger.LogInformation(invocation.ReturnValue.ToString()); } }}
Disclaimer: The content of this article is sourced from the internet. The copyright of the text, images, and other materials belongs to the original author. The platform reprints the materials for the purpose of conveying more information. The content of the article is for reference and learning only, and should not be used for commercial purposes. If it infringes on your legitimate rights and interests, please contact us promptly and we will handle it as soon as possible! We respect copyright and are committed to protecting it. Thank you for sharing.(Email:[email protected])