程序集扫描
扫描类型
var dataAccess = Assembly.GetExecutingAssembly(); builder.RegisterAssemblyTypes(dataAccess) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces();
过滤类型
var dataAccess = Assembly.GetExecutingAssembly(); var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(dataAccess) .Where(t => t.Name.EndsWith("IG")) .PropertiesAutowired() //设置属性自动注入 .PublicOnly() //过滤修饰符,如 internal 类型的类或属性不被注入 .Except<AssemblyBIG>() //过滤类型 .AsImplementedInterfaces(); //注入为所依赖的接口类型 var container = builder.Build(); IAssemblyAIG aIG = container.Resolve<IAssemblyAIG>(); Console.WriteLine(aIG.Get());
扫描模块与模块注入
var builder = new ContainerBuilder(); var assembly = typeof(AssemblyAIG).Assembly; //通过程序集扫描模块 builder.RegisterAssemblyModules(assembly); //模块注入 builder.RegisterModule(new AssemblyTransportModule() { ObeySpeedLimit = true }); var container = builder.Build(); IAssemblyAIG aIG = container.Resolve<IAssemblyAIG>(); Console.WriteLine(aIG.Get()); IDriver driver = container.Resolve<IDriver>(); driver.Do(); public class AssemblyTransportModule : Module { public bool ObeySpeedLimit { get; set; } protected override void Load(ContainerBuilder builder) { builder.RegisterType<AssemblyBIG>().As<IAssemblyBIG>(); builder.Register(c => new AssemblyAIG { BIG = c.Resolve<IAssemblyBIG>() }) .As<IAssemblyAIG>(); if (ObeySpeedLimit) builder.Register(c => new AssemblyBIG()).As<IDriver>(); else builder.Register(c => new AssemblyAIG()).As<IDriver>(); } }
#生命周期释放
var builder = new ContainerBuilder(); builder.RegisterType<SomeComponent>() .OnRelease(instance => instance.CleanUp()); //在释放时对示例调用指定释放方法 builder.RegisterType<SomeComponent>().ExternallyOwned(); //禁止自动释放,即生命周期由对象自己管理或者由调用主动释放
#容器创建回调
var builder = new ContainerBuilder(); builder .RegisterBuildCallback(c => c.Resolve<DbContext>()); // The callback will run after the container is built // but before it's returned. var container = builder.Build();