简体   繁体   中英

How do I set a property on a base class for all classes that subclass it, using structuremap?

I have numerous (60 or 70) classes that subclass a shared base class. This base class exposes a property of type ICacheProvider that needs to be set when each of the superclasses is registered with structuremap. I am using structuremap version 2.6.1. Currently, I am setting the property for each superclass, thus:

        For<IBusinessRule<IEnumerable<int>>>()
            .Use<ManufacturersWithReviewsRule>()
            .Named(NamedRuleConstants.ManufacturersWithReviews)
            .Setter<ICacheProvider>().Is(ObjectFactory.GetNamedInstance<ICacheProvider>(CacheConstants.IndexCacheKeyPrefix));

        For<IBusinessRule<IEnumerable<int>>>()
            .Use<ManufacturersWithOwnersReviewsRule>()
            .Named(NamedRuleConstants.ManufacturersWithOwnersReviews)
            .Setter<ICacheProvider>().Is(ObjectFactory.GetNamedInstance<ICacheProvider>(CacheConstants.IndexCacheKeyPrefix));

        For<IBusinessRule<IEnumerable<int>>>()
            .Use<ManufacturersWithLivingWithItRule>()
            .Named(NamedRuleConstants.ManufacturersWithLivingWithIt)
            .Setter<ICacheProvider>().Is(ObjectFactory.GetNamedInstance<ICacheProvider>(CacheConstants.IndexCacheKeyPrefix));

(ManufacturersWithReviewsRule, ManufacturersWithOwnersReviewsRule, ManufacturersWithLivingWithItRule each subclass BaseBusinessRule)

What I want to do is specify the:

.Setter<ICacheProvider>().Is(ObjectFactory.GetNamedInstance<ICacheProvider>(CacheConstants.IndexCacheKeyPrefix));

a single time for all, allowing me to set it individually where necessary should I require a different ICacheProvider.

Is this possible using structuremap 2.6.1? I can find no way of doing it.

For a similar concept, when I want to set any object having some type of property on a default level, I use something like this

// during the ObjectFactory.Initialize
x.SetAllProperties(set => set.OfType<ICacheProvider>());

// something more...
// this way the instance could be shared 
x.For<ICacheProvider>()
    // as a singleton
    .Singleton()
    .Use<DefaultCacheProvider>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM