nopCommerce实现的功能如下:
需要注入的类:
public class CommonSettings : ISettings { public bool UseSystemEmailForContactUsForm { get; set; } public bool UseStoredProceduresIfSupported { get; set; } public bool HideAdvertisementsOnAdminArea { get; set; } }
通过 ISettingService 取得该类:
public interface ISettingService { T LoadSetting<T>(int storeId = 0) where T : ISettings, new(); }
AutoFac的注册方法:
builder.RegisterType<SettingService>().As<ISettingService>() .WithParameter(ResolvedParameter.ForNamed<ICacheManager>("nop_cache_static")) .InstancePerLifetimeScope();
builder.RegisterSource(new SettingsSource()); public class SettingsSource : IRegistrationSource { static readonly MethodInfo BuildMethod = typeof(SettingsSource).GetMethod( "BuildRegistration", BindingFlags.Static | BindingFlags.NonPublic); public IEnumerable<IComponentRegistration> RegistrationsFor( Service service, Func<Service, IEnumerable<IComponentRegistration>> registrations) { var ts = service as TypedService; if (ts != null && typeof(ISettings).IsAssignableFrom(ts.ServiceType)) { var buildMethod = BuildMethod.MakeGenericMethod(ts.ServiceType); yield return (IComponentRegistration)buildMethod.Invoke(null, null); } } static IComponentRegistration BuildRegistration<TSettings>() where TSettings : ISettings, new() { return RegistrationBuilder .ForDelegate((c, p) => { return c.Resolve<ISettingService>().LoadSetting<TSettings>(); }) .InstancePerLifetimeScope() .CreateRegistration(); } public bool IsAdapterForIndividualComponents { get { return false; } } }
构造器注入直接注入CommonSettings即可:
private readonly CommonSettings _commonSettings; public SitemapGenerator(CommonSettings commonSettings) { _commonSettings = commonSettings; }
请问,使用Castle Winsor 该如何注册?
IWindsorContainer.Register(Classes.FromAssembly(assembly).IncludeNonPublicTypes().BasedOn<ISettings>().WithService.Self().WithService.DefaultInterfaces().LifestyleTransient());
Castle.Windsor:上面代码表示将程序集assembly中实现了ISettings接口的类注册到Container中。
实现的不一样。
在Nop中,注入 CommonSettings 时自动从ISettingService将数据Load出来了。而你的代码无法自动Load。
@东至: 确保注册 ISettings 和注入 CommonSettings 用的是同一个 Container
楼主,能给我解释下 autofac 的这里是怎么实现的吗?没看懂。。。。。
我不知道为什么实现了 ISettings 接口为什么就可以起作用。麻烦解释下