How to use memory caching in Asp.Net core 2 without constructor - caching

In Asp.Net application(Class library project) , caching with using System.Runtime.Caching was working fine without use constructor.
protected ObjectCache ResponseCache
{
get
{
return MemoryCache.Default;
}
}
Now, I want to use same as in Asp.Net CORE application without constructor.
As Asp.Net CORE 2 is not supporting namespace System.Runtime.Caching and replace it Microsoft.Extensions.Caching.Memory
I use this MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()) but it create always new object which clear all old cache memories.
Note: I'm looking solution for without defined constructor.

You have to implement it in ASP.NET Core way. That is, using dependency injection. You have to register the MemoryCache in the ConfigureServices method in the Startup class as:
services.AddMemoryCache();
then you need to inject the IMemoryClass in your controller to access it. You can check the docs for more details: Cache in-memory in ASP.NET Core
That way, you will not be worrying much on passing dependencies to the constructor since the DI container will handle it automatically.

Related

What is alternate for CreatePerOwinContext in .net core 2.1

I had a webapi in which I was using app.CreatePerOwinContext in startup.cs file but I want to migrate that webapi to .net core 2.1. So I have stuck at this point as I can't fine any alternate for CreatePerOwinContext.
Here is my webapi code:
public static UserManager<IdentityUser> Create(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
{
var manager = new UserManager<IdentityUser>(new UserStore());
return manager;
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<UserManager<IdentityUser>>(Create);
...
}
So how can I convert the above code in .net core 2.1?
That method was used as a service locator to load up dependencies and then access them throughout your code. Service location on its own is considered an anti-pattern, and is not recommended for use in the vast majority of real world situations.
Instead, people use IOC containers now to manage their dependency injection. In ASP.NET MVC Core, there's now a lightweight and "good enough" IOC container provided for you as part of the framework.
Microsoft provides an overview in this article, but the short version is that in your Startup.cs you register your dependency tree under ConfigureServices (usually using an extension method so Startup.cs doesn't get too large).
After you've registered your dependencies, you load them either through property injection, constructor injection, or method parameter injection. This results in cleaner code that is more maintainable than standard service location.
Edit:
If you truly insist on managing a service locator either because the technical debt is acceptable or because the business case warrants the current design, then I suggest you transition your work from OwinContext over to HttpContext.
In ASP.NET Core, you access the HttpContext by injecting the HttpContextAccessor into your class, and changing your OwinContext calls to pull from the key value store in HttpContext.
Instructions for injecting HttpContextAccessor can be found in this SO answer. Simply store KVPs using HttpContext.Current.Application["myObject"].
I don't recommend doing this, but I'm willing to share it because I understand the reality of deadlines vs the idealism of architecture.

Structuremap - dependency injection - EF Core DBContext lifetime per request

Has anyone had any luck setting up an EF Core DBContext with Structuremap "correctly" (what is correctly?)
DBContext needs to be a singleton across the lifetime of the request.
I understand that the default lifecycle is Transient. I understand that that will get a nested container, which effectively means "per request" when running under web api / mvc? (see this)
But, looking at this code, isn't the dbcontext going to be an Application Lifetime singleton?
public class DistributedTaskRegistry : Registry
{
public DistributedTaskRegistry()
{
For<DistributedTaskDbContext>().Use(() => new DistributedTaskDbContextFactory().CreateDbContext(null));
For<IDistributedTaskRepository>().Use<DistributedTaskRepository>();
}
}
NB this is a "legacy" .Net Framework 4.7 Web Api using EF Core
Edit What happened to HttpContextScoped?
Confirmed: the default lifetime is transient, and with StructureMap that means Per Request Lifetime.
If you want an app lifetime Singleton you need to specify it.
For<IDistributedTaskRepository>().Use<DistributedTaskRepository>().Singleton();

NServiceBus and ApiController

i try to configure my NServiceBus for a WebApi. I've tried this one: https://coderkarl.wordpress.com/2012/03/16/injecting-nservicebus-into-asp-net-webapi/
The Problem is the Syntax has been changed in the newest NServiceBus-Versin. I can't use the Functions for the Configure-Class because they will be removed in further Versions. The new way to configure the Bus is using the BusConfiguration-Class but i have no idea how.
Here is the older Code:
public static Configure ForWebApi(this Configure configure)
{
// Register our http controller activator with NSB
configure.Configurer.RegisterSingleton(typeof(IHttpControllerActivator),
new NSBHttpControllerActivator());
// Find every http controller class so that we can register it
var controllers = Configure.TypesToScan
.Where(t => typeof(IHttpController).IsAssignableFrom(t));
// Register each http controller class with the NServiceBus container
foreach (Type type in controllers)
configure.Configurer.ConfigureComponent(type, ComponentCallModelEnum.Singlecall);
// Set the WebApi dependency resolver to use our resolver
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NServiceBusResolverAdapter(configure.Builder));
// Required by the fluent configuration semantics
return configure;
}
And Application_Start():
AreaRegistration.RegisterAllAreas();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory("Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
Configure.WithWeb()
.DefaultBuilder()
.ForWebApi() // <------ here is the line that registers it
.Log4Net()
.XmlSerializer()
.MsmqTransport()
.IsTransactional(false)
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
Does someone has managed it for the NServiceBus Version 5?
As wlabaj says, the documentation on the particular website says it all. Almost.
We use AutoFac so we don't need any direct reference to IBus or ISendOnlyBus and therefor we do this
ContainerBuilder builder = new ContainerBuilder();
var container = builder.Build();
configuration.UseContainer<AutofacBuilder>(x => x.ExistingLifetimeScope(container));
What we do in WebAPI and ASP.NET applications is this
NServiceBus.Bus.CreateSendOnly(configuration);
Because it's not a good practice to expect reply messages to come back after sending them.
Here you can see 3.0 vs 4.0 vs 5.0 configuration syntax. At the top of the page you have a link to download code samples.
The examples are for ASP .NET though, so you'll need to tweak it slightly for WebAPI. Let me know if you need further help with that.
ForWebApi was never a part of NServiceBus, this was an extension method from the sample that was used to configure NServiceBus dependency resolver to instantiate controllers. The way how it was done is shown here.
There is no need to use NServiceBus resolver since it is just a wrapper around another container. By default it uses Autofac, so you can just use Autofac to work for you in the whole application.
Autofac WebAPI integration is properly described in the documentation.
NServiceBus documentation has a page about using your own container.
This is a very well known setup that you can easily implement.

ASP.NET MVC Views Dependency Injection without DependencyResolver?

Is it possible to inject dependencies into an MVC ViewPage (must support layout pages) without using DependencyResolver?
I would rather not use DependencyResolver at all (I had major problems when injecting NH sessions into ActionFilters in the past (leaking all over the place)). However, I'm not sure if there is an alternative?
The other complexity I have is that the DependencyResolver needs to be tenant aware (each tenant has its own (StructureMap) container). I'm currently doing this by passing in a lazy instance of my tenant container resolver (seems this is necessary otherwise the resolver is cached):
public SmDependencyResolver(Func<ISiteContainerResolver> containerResolver)
{
this.containerResolver = containerResolver;
}
public object GetService(Type serviceType)
{
var container = containerResolver().Resolve();
If I end up using DependencyResolver should I ditch my StructureMap controller factory since it looks like DependencyResolver handles this too?
Thanks
Ben
Given that the DependencyResolver is used by so many aspects of the ASP.NET MVC framework for dependency injection your life will be easier if you use it - as you say it means you don't need your own versions of things like the controller factory.
That said, the framework is very flexible and it is always open for you to plug in your own version of things - I just prefer to create as little of my own code as possible on the KISS principle.

Difference between use of a controller factory and NinjectHttpApplication?

Using Ninject 2 MVC 3. Correct me if i am wrong but ive seen two way of using Ninject in an MVC 3 application. We can use a new controller factory which is like ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); or using NinjectHttpApplication and then configure the kernel.
I was wondering what difference between use of a controller factory and NinjectHttpApplication to configure the binding for DI?
And what are the best place to setup DI ?
NinjectHttpApplication calls ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()) internally.
But additionally it sets up various bindings and provides many new features. In other words it's less work and adds new features. Best you read my blog post about the MVC3 extension. http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/

Resources