c# - StructureMap对象重新加载

c# - StructureMap对象重新加载,第1张

为了简化,我有一个AppSettings:IAppSettings类,它在应用程序启动时初始化:

ObjectFactory.Initialize(x =>
{
    x.Scan(scan => {
        scan.TheCallingAssembly();

        scan.WithDefaultConventions();
    });
    x.AddRegistry<DataAccessRegistry>();
    x.AddRegistry<AuthorizationRegistry>();

    x.For<IAppSettings>()
        .Use<AppSettings>()
        .Ctor<Dictionary<string, string>>()
            .Is(ctx =>
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                var sessionFactory = ctx.GetInstance<ISessionFactory>();
                using (var session = sessionFactory.OpenSession())
                using (var tx = session.BeginTransaction())
                {
                    // query the SETTINGS table
                    foreach (Setting _setting in session.QueryOver<Setting>().List())
                    {
                        dict[_setting.Key] = _setting.Value;
                    }
                    tx.Commit();
                }
                return dict;
            });

    x.UseDefaultStructureMapConfigFile = false;
});

因此,在创建需要设置的类时,我只需使用以下

public class AccessDataService {
    private IAppSettings settings;

    public AccessDataService(IAppSettings p_appSettings) {
        settings = p_appSettings;
    }
....
}

和structuremap很好地将对象注入到我的类实例中。

但是,我希望能够明确地触发数据库设置重新加载,所以我想知道是否有办法告诉structuremap清除AppSettings的所有现有对象并重新创建它们,再次从DB加载设置?

干杯

最佳答案:

1 个答案:

答案 0 :(得分:2)

每次需要刷新时都可以使用EjectAllInstancesOf方法:

ObjectFactory.EjectAllInstancesOf<IAppSettings>();
ObjectFactory.Inject<IAppSettings>(*your new object*);
本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复