Autofac 的点滴
泛型类型的注册和使用
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | public interface IRepository<T> where T: class { } public interface ISchoolDetailRepository : IRepository<SchoolDetail> { } public abstract class RepositoryBase<T> where T : class { private LearningCompactPilotContext _dataContext; private readonly IDbSet<T> _dbset; protected RepositoryBase(IDatabaseFactory databaseFactory) { DatabaseFactory = databaseFactory; _dbset = DataContext.Set<T>(); } protected IDatabaseFactory DatabaseFactory { get ; private set ; } protected LearningCompactPilotContext DataContext { get { return _dataContext ?? (_dataContext = DatabaseFactory.Get()); } } //... more code } //如何注册 builder.RegisterGeneric( typeof (RepositoryBase<>)) .As( typeof (IRepository<>)); //如何使用 public class SomeService { private readonly IRepository<SomeEntity> _repository; public SchoolService(IRepository<SomeEntity> repository) { this ._repository= repository; } } |
如何注入泛型的Nloggger<T> AS ILogger(动态类型注入)
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | public class LoggingModule : Autofac.Module { private static void InjectLoggerProperties( object instance) { var instanceType = instance.GetType(); // Get all the injectable properties to set. // If you wanted to ensure the properties were only UNSET properties, // here's where you'd do it. var properties = instanceType .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.PropertyType == typeof (ILog) && p.CanWrite && p.GetIndexParameters().Length == 0); // Set the properties located. foreach ( var propToSet in properties) { propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null ); } } private static void OnComponentPreparing( object sender, PreparingEventArgs e) { e.Parameters = e.Parameters.Union( new [] { new ResolvedParameter( (p, i) => p.ParameterType == typeof (ILog), (p, i) => LogManager.GetLogger(p.Member.DeclaringType) ), }); } protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { // Handle constructor parameters. registration.Preparing += OnComponentPreparing; // Handle properties. registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance); } } |
相同接口不同实现的如何注册使用
适配模式和装饰模式注册
适配模式
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 | var builder = new ContainerBuilder(); // Register the services to be adapted builder.RegisterType<SaveCommand>() .As<ICommand>() .WithMetadata( "Name" , "Save File" ); builder.RegisterType<OpenCommand>() .As<ICommand>() .WithMetadata( "Name" , "Open File" ); // Then register the adapter. In this case, the ICommand // registrations are using some metadata, so we're // adapting Meta<ICommand> instead of plain ICommand. builder.RegisterAdapter<Meta<ICommand>, ToolbarButton>( cmd => new ToolbarButton(cmd.Value, ( string )cmd.Metadata[ "Name" ])); var container = builder.Build(); // The resolved set of buttons will have two buttons // in it - one button adapted for each of the registered // ICommand instances. var buttons = container.Resolve<IEnumerable<ToolbarButton>>(); |
装饰模式
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 | var builder = new ContainerBuilder(); // Register the services to be decorated. You have to // name them rather than register them As<ICommandHandler>() // so the *decorator* can be the As<ICommandHandler>() registration. builder.RegisterType<SaveCommandHandler>() .Named<ICommandHandler>( "handler" ); builder.RegisterType<OpenCommandHandler>() .Named<ICommandHandler>( "handler" ); // Then register the decorator. The decorator uses the // named registrations to get the items to wrap. builder.RegisterDecorator<ICommandHandler>( (c, inner) => new CommandHandlerDecorator(inner), fromKey: "handler" ); var container = builder.Build(); // The resolved set of commands will have two items // in it, both of which will be wrapped in a CommandHandlerDecorator. var handlers = container.Resolve<IEnumerable<ICommandHandler>>(); |
还是使用泛型
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 | var builder = new ContainerBuilder(); // Register the open generic with a name so the // decorator can use it. builder.RegisterGeneric( typeof (CommandHandler<>)) .Named( "handler" , typeof (ICommandHandler<>)); // Register the generic decorator so it can wrap // the resolved named generics. builder.RegisterGenericDecorator( typeof (CommandHandlerDecorator<>), typeof (ICommandHandler<>), fromKey: "handler" ); var container = builder.Build(); // You can then resolve closed generics and they'll be // wrapped with your decorator. var mailHandlers = container.Resolve<IEnumerable<ICommandHandler<EmailCommand>>>(); |
01 | |
参考
MVC 4 Autofac and Generic Repository pattern
作者:旭东
出处:http://www.cnblogs.com/HQFZ
关于作者:专注于微软平台项目架构、管理和企业解决方案。现主要从事WinForm、ASP.NET、WPF、WCF、等方面的项目开发、架构、管理。如有问题或建议,请不吝指教!
本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以联系我,非常感谢。
如果您该文觉得不错或者对你有帮助,请点下推荐,让更多的朋友看到,谢谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?