开发者

Using DI to cache a query for application lifetime

Using a DI container (in this case, Ninject) is it possible - - or rather, wise to cache a frequently used object for the entire application lifetime (or at least until it is refreshed)?

To cite example, say I have a Template. There are many Template objects, but each user will inherit at least the lowest level one. This is immutable and will never change without updating everything that connects to it (so it will only change on administration demand, never based on user input). It seems foolish to keep querying the database over and over for information I know is not changed.

Would caching this be best done in my IoC container, or should I outsource it to something else?

I already store ISessionFactory (nHibernate) as a Singleton. But that's a little bit different because it doesn't include a query to the database, just the back-end to open and close ISession objects to it.

So basically I would do so开发者_运维问答mething like this..

static class Immutable
{
 [Inject]
 public IRepository<Template> TemplateRepository { get; set; }

 public static ITemplate Template { get; set; }

 public void Initialize()
 {
  if(Immutable.Template == null)
  {
   Immutable.Template = TemplateRepository.Retrieve(1); // obviously better logic here.
  }
}

class TemplateModule : Module
{
 public void Load()
 {
   Bind<ITemplate>().ToMethod(() => Immutable.Initialize())InSingletonScope();
 }
}

Is this a poor approach? And if so, can anyone recommend a more intelligent one?


I'd generally avoid using staticness and null-checking from your code - create normal classes without singleton wiring by default and layer that aspect on top via the container. Ditto, remove reliance on property injection - ctor injection is always better unless you have no choice

i.e.:

class TemplateManager
{
 readonly IRepository<Template> _templateRepository;

 public TemplateManager(IRepository<Template> templateRepository)
 {
     _templateRepository = templateRepository;
 }

 public ITemplate LoadRoot()
 {
  return _templateRepository.Retrieve(1); // obviously better logic here.
 }
}

class TemplateModule : Module
{
 public void Load()
 {
   Bind<ITemplate>().ToMethod(() => kernel.Get<TemplateManager>().LoadRoot()).InSingletonScope();
 }
}

And then I'd question whether TemplateManager should become a ninject provider or be inlined.

As for the actual question... The big question is, how and when do you want to control clearing the cache to force reloading if you decided that the caching should be at session level, not app level due to authorization influences on the template tree? In general, I'd say that should be the Concern of an actual class rather than bound into your DI wiring or hardwired into whether a class is a static class or is a Singleton (as in the design pattern, not the ninject Scope).

My tendency would be to have a TemplateManager class with no static methods, and make that a singleton class in the container. However, to get the root template, consumers should get the TemplateManager injected (via ctor injection) but then say _templateManager.GetRootTemplate() to get the template.

That way, you can:

  1. not have a reliance on fancy ninject providers and/or tie yourself to your container
  2. have no singleton cruft or static methods
  3. have simple caching logic in the TemplateManager
  4. vary the Scoping of the manager without changing all the client code
  5. have it clear that getting the template may or may not be a simple get operation

i.e, I'd manage it like so:

class TemplateManager
{
 readonly IRepository<Template> _templateRepository;

 public TemplateManager(IRepository<Template> templateRepository)
 {
     _templateRepository = templateRepository;
 }

 ITemplate _cachedRootTemplate;    
 ITemplate FetchRootTemplate()
 { 
     if(_cachedRootTemplate==null)
           _cachedRootTemplate = LoadRootTemplate();
     return _cachedRootTemplate;
 }

 ITemplate LoadRoot()
 {
  return _templateRepository.Retrieve(1); // obviously better logic here.
 }
}

register it like so:

class TemplateModule : Module
{
 public void Load()
 {
   Bind<TemplateManager>().ToSelf().InSingletonScope();
 }
}

and then consume it like so:

class TemplateConsumer
{
 readonly TemplateManager _templateManager;

 public TemplateConsumer(TemplateManager templateManager)
 {
     _templateManager = templateManager;
 }

 void DoStuff()
 {
      var rootTempalte = _templateManager.FetchRootTemplate();

Wild speculation: I'd also consider not having a separate IRepository being resolvable in the container (and presumably having all sorts of ties into units of work). Instead, I'd have the TemplateRepository be a longer-lived thing not coupled to an ORM layer and Unit Of Work. IOW having a repository and a Manager none of which do anything well defined on their own isnt a good sign - the repository should not just be a Table Data Gateway - it should be able to be the place that an Aggregate Root such as Templates gets cached and collated together. But I'd have to know lots more about your code base before slinging out stuff like that without context!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜