2

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.

Jason
  • 3,599
  • 10
  • 37
  • 52
  • See this answer: http://stackoverflow.com/a/9549409/20047 and the linked post (http://codebetter.com/jeremymiller/2009/01/16/creating-policies-for-setter-injection-in-structuremap/) – jeroenh Jan 03 '14 at 12:00
  • My first impression is that you should ditch the base class completely and implement caching (a cross cutting concern) using a decorator. – Steven Jan 03 '14 at 14:15

1 Answers1

1

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>();
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335