Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap Open Generics and CacheBy Singleton

I have a number of repositories that inherit from a base class Repository. Currently I am registering in-memory implementations with Structure map like this (and it's working great):

ForRequestedType<Repository<Timeslot>>()
    .TheDefaultIsConcreteType<InMemoryRepository<Timeslot>>()
    .AsSingletons();

ForRequestedType<Repository<Appointment>>()
    .TheDefaultIsConcreteType<InMemoryRepository<Appointment>>()
    .AsSingletons();

I thought it would be nice to use StructureMap's support for Open Generics to register all these (the number is growing) so when I add a new Repository, I wouldn't have to update the ServiceRegistry.

I tried this:

ForRequestedType(typeof (Repository<>))
    .CacheBy(InstanceScope.Singleton)
    .TheDefaultIsConcreteType(typeof (InMemoryRepository<>));

That doesn't seem to be working. It doesn't throw an exception, but it acts like the repositories aren't singletons. Anything added to them doesn't persist during the application's life cycle.

Is it possible to register an open generic, and have the implementations cached by a singleton scope? This is an ASP.NET MVC app, and I just want the repositories to work until the application is restarted.

like image 975
Lance Fisher Avatar asked Sep 18 '26 13:09

Lance Fisher


1 Answers

I had a similar scenario and was able to address it successfully using the newer fluent syntax (using StructureMap 2.6.3.0):

x.For(typeof(Repository<>))
 .LifecycleIs(InstanceScope.Singleton)
 .Use(typeof(InMemoryRepository<>));
like image 167
Cristian Lupascu Avatar answered Sep 22 '26 00:09

Cristian Lupascu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!