Registering decorators with primitive configuration dependencies in Simple Injector

心已入冬 提交于 2019-12-01 22:37:22

Simple Injector does not easily allow registering decorators that contain primitive configuration values. There are multiple ways to extend Simple Injector to enable such behavior, but I would say that there are easier solutions.

Except for extending Simple Injector, you've basically got two options here. Either you fall back to manual construction of this part of the object graph, or you extract the group of primitive configuration values into its own configuration object, which you can register as singleton in the container.

You can manually construct the decorator and its decoratee as follows:

container.RegisterSingleton<IAppSettingsLoader>(
    new CachedAppSettingsLoader(
        "AuthorizationRecords", 
        cacheItemPolicy, 
        MemoryCache.Default, 
        new FileAppSettingsLoader()));

The other option is to extract the configuration values into its own class, which might be good idea anyway:

public class CachedAppSettingsLoaderSettings
{
    public ObjectCache Cache;
    public CacheItemPolicy Policy;
    public string CacheKey;
}

public class CachedAppSettingsLoader : IAppSettingsLoader
{
    private readonly CachedAppSettingsLoaderSettings settings;
    private readonly IAppSettingsLoader decoratee;

    public CachedAppSettingsLoader(
        CachedAppSettingsLoaderSettings settings, IAppSettingsLoader decoratee)
    {
        ...
    }
}

After this refactoring, you can register your types as follows:

container.Register<IAppSettingsLoader, FileAppSettingsLoader>(Lifestyle.Singleton);
container.RegisterDecorator<IAppSettingsLoader, CachedAppSettingsLoader>(
    Lifestyle.Singleton);
container.RegisterInstance(new CachedAppSettingsLoaderSettings
{
    Cache = MemoryCache.Default,
    Policy = new CacheItemPolicy { ... },
    CacheKey = "AuthorizationRecords" 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!