MichaCo / CacheManager

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features.
http://cachemanager.michaco.net
Apache License 2.0
2.35k stars 456 forks source link

Unity Dependency Injection with Unity MVC #178

Closed pgardella closed 7 years ago

pgardella commented 7 years ago

Good afternoon!

This may be a problem with my knowledge of DI at this point. If so, my apologies!

This is with Cache Manager 1.1.1

I'm following your example of the Single Page ToDo except with Unity MVC insead of Unity WebAPI.

In Global.asax.cs during app initialization (Application_Start), I create the IUnityContainer and register the Cache Manager instance:

var container = new UnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
var cacheConfig = ConfigurationBuilder.BuildConfiguration(settings =>
       {
                settings
                    .WithSystemRuntimeCacheHandle(false)
                    .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromSeconds(3600));
            });

            container.RegisterType(
                typeof(ICacheManager<>),
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(
                    (c, t, n) => CacheFactory.FromConfiguration(
                        t.GetGenericArguments()[0], cacheConfig)));

Then in the helper class (which is where I use the cache), I add a property with the Dependency attribute on:

[Dependency]
public ICacheManager<List<Term>> AllTermCache { get; set; }

In my method, I get a Null Reference Exception anytime I try to use AllTermCache, whehter I'm PUTing or checking if it exists:

List<Term> testvar = new List<Term>();

AllTermCache.Put("Test", testvar);

or

if (AllTermCache.Exists("Terms")) {
    _log.Debug("Terms found in cache. Returning cached values.");
    return (List<Term>)AllTermCache.Get("Terms");
 }

What did I miss in the example code on GitHub?

MichaCo commented 7 years ago

Yeah this seems to have nothing todo with CacheManager. Anyways, did you also change the ToDoController to extend from Controller (MVC) instead of ApiController (API)?

pgardella commented 7 years ago

Thanks. Found the problem, which should have been obvious. If you are using the MVC Unity container, you need to put the caches somewhere in the MVC code.

I had it in a separate helper class, outside the Controller.