首页新闻找找看学习计划

想用Castle Windsor实现nopCommerce中 AutoFac 注册 ISettings 的功能

0
悬赏园豆:100 [待解决问题]

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 该如何注册?

东至的主页 东至 | 初学一级 | 园豆:16
提问于:2015-08-09 21:42
< >
分享
所有回答(3)
0
IWindsorContainer.Register(Classes.FromAssembly(assembly).IncludeNonPublicTypes().BasedOn<ISettings>().WithService.Self().WithService.DefaultInterfaces().LifestyleTransient());

Castle.Windsor:上面代码表示将程序集assembly中实现了ISettings接口的类注册到Container中。

nianhua11 | 园豆:736 (小虾三级) | 2015-09-01 17:09

实现的不一样。

在Nop中,注入 CommonSettings 时自动从ISettingService将数据Load出来了。而你的代码无法自动Load。

支持(0) 反对(0) 东至 | 园豆:16 (初学一级) | 2015-09-17 14:10

@东至: 确保注册 ISettings 和注入 CommonSettings 用的是同一个 Container

支持(0) 反对(0) nianhua11 | 园豆:736 (小虾三级) | 2015-09-19 08:57
0

随碟附送520 | 园豆:206 (菜鸟二级) | 2015-12-30 09:51
0

楼主,能给我解释下 autofac 的这里是怎么实现的吗?没看懂。。。。。

我不知道为什么实现了 ISettings 接口为什么就可以起作用。麻烦解释下

LoveCoder | 园豆:7 (初学一级) | 2016-07-29 14:18
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册