I have an ASP.NET web application that I created from Visual Studio 2015 Community Edition. The .NET Framework is 4.6.1.
I have no idea which version of ASP.NET my web application is using ASP.NET MVC 4? ASP.NET MVC 5? It's not mentioned anywhere.
I'm trying to register IMemoryCache
service (from Microsoft.Extensions.Caching.Memory
) into my Microsoft Unity container. However, anything I found about it on Google refers to adding services.AddCaching()
in a Startup.cs
file.
I don't have a Startup.cs
file. I only see Global.asax
. Furthermor, all my custom dependencies are registered within UnityConfig.cs
which was provided when installing the NuGet package Unity.Mvc
which is a Microsoft Unity bootstrapper for ASP.NET by Microsoft.
Any help appreciated.
Edit:
Here's a screenshot of my project:
In .NET Core AddMemoryCache Extensions looks like this:
services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());
So in .Net Framework you can use something like this (for Autofac):
builder.RegisterType<MemoryCache>().As<IMemoryCache>().SingleInstance();
UPD: However MemoryCache
dependends on IOptions<>
you should register it too:
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptions<>)).SingleInstance();
builder.RegisterGeneric(typeof(OptionsManager<>)).As(typeof(IOptionsSnapshot<>)).InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(OptionsMonitor<>)).As(typeof(IOptionsMonitor<>)).SingleInstance();
builder.RegisterGeneric(typeof(OptionsFactory<>)).As(typeof(IOptionsFactory<>));
builder.RegisterGeneric(typeof(OptionsCache<>)).As(typeof(IOptionsMonitorCache<>)).SingleInstance();
The things you are referring to are part of the ASP.Net Core (ASP.Net 5)
In the new version you no longer have a Global.asax file, you have a new Startup processed defined in a Startup class. Also, DI is standard, so things work in a different way now. So either upgrade to the latest version of ASP.Net or apply use the DI solutions for the older version:
RESOLVING DEPENDENCIES IN ASP.NET MVC 5 USING UNITY CONTAINER
Also the package you are using is for the new ASP.NET version.
Introduction to ASP.NET Core
If you are using Unity, you can do something similar like this in UnityConfig.cs
var memoryCache = new MemoryCacheService(new MemoryCacheOptions());
container.RegisterInstance<IMemoryCache>(memoryCache);
create your MemoryCacheService
public class MemoryCacheService : MemoryCache
{
public MemoryCacheService(IOptions<MemoryCacheOptions> optionsAccessor) : base(optionsAccessor)
{
}
}
yourcontroller
private readonly IMemoryCache _memoryCacheService;
public yourcontroller(IMemoryCache memoryCacheService)
{
_memoryCacheService = memoryCacheService;
}
public IHttpActionResult AddCacheItem(string cacheKey)
{
_memoryCacheService.Set(cacheKey, DateTime.Now.Ticks );
var temp = _memoryCacheService.Get(cacheKey);
return Ok(temp);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With