Reputation: 5565
It is chance define some singleton variable in asp.net mvc3 ? I want define it (probably in global.asax) and then in controllers get it, by IOC resolver (structureMap)
Simple: I want have one property with same data for all users, not dependency on request, session, ... For example At first start of MVC application I set DateTime value into this property and then all requests can view this property and modified this property in controllers.
Upvotes: 0
Views: 2247
Reputation: 6898
Just use StructureMap to create your controllers using a dependency resolver like outlined in this blog post. Inject not the variable directly but an instance that holds that variable:
public class GlobalScope
{
public String Variable { get; set; }
}
Now you can inject GlobalScope into your controllers and set/get the Variable but keep in mind that you're in a multi threaded environment where read and write access to variables must be synchronized or you run into some weird race conditions.
Upvotes: 4
Reputation: 329
Any Variable or class that is public Static resides in the AppDomain and is globally availiable for use in all sessions. So you could simply:
Have been known to use all 3 including using a Common Service Location to find the IOC container, which makes life so easy.
Hope this Helps
Upvotes: 1
Reputation: 2447
Your IoC container probably extends the concept of a singleton. Ninject does with InSingletonScope. This would work better than a static app variable as any libraries would have to know about your application, and then you have circular references.
Upvotes: 0
Reputation: 10230
You could store the data as a static member of the Application class. See this article - Application State in ASP.NET
Upvotes: 0
Reputation: 30115
First of all you can use simple singleton pattern in .net wihich is not related to asp.net or asp.net mvc specific things at all.
If you want to use IoC, you can register you class instance like single instance and IoC will return you always only single class instance. Put necessary properties to this instance and edit it. Initialization will be on the type registration step:
Sample in Autofac:
builder.Register(MySingleton.Instance);
and with Lazy initialization:
builder.Register(c => MySingleton.Instance);
Also you can register type and IoC will control your type initialization, but in this case you can't set your default value during initialization:
builder.RegisterType<MyType>().SingleInstance();
Upvotes: 1