I'm using the new .NET 4.0 Caching API, ObjectCache. I've asked a few questions on this area the last few days, and i've hinted to this issue - but thought it's worthwhile to break it out into it's own question.
Because the class is abstract and all the methods are virtual, this means we can create our own custom cache providers.
According to MSDN, ObjectCache does not have to be a singleton, and you can create multiple instances of it in your application.
But to me, this sounds like we need to manage the instantiation and lifetime of this object as well?
I have an ASP.NET MVC 3 Web Application, with StructureMap as my dependency injection container.
I want to have a single, shared cache for my entire web application.
So, i create a very simple class which wraps the ObjectCache class, and provides the unboxing in the methods implementation.
The class takes an instance of ObjectCache in the ctor, and sets this to a private static instance of the cache, which the methods (Add, Get, etc) work off.
E.g
public class CacheManager
{
private static ObjectCache _cache;
public CacheManager(ObjectCache cache)
{
_cache = cache;
}
// Add, Get, Remove methods work off _cache instance.
}
Now, here's my DI registry:
For<CacheManager>().Singleton().Use<CacheManager>().Ctor<ObjectCache>("cache").Is(MemoryCache.Default);
In english: When something requests a CacheManager instance, use a singleton instance, and set the ObjectCache parameter to be a MemoryCache instance.
So there's what i have, now the questions:
If i have a class to wrap the ObjectCache, does this class need to be a singleton?
MSDN says ObjectCache is thread-safe, but now that i'm using a singleton, do i need any type of locking to keep the thread safety?
Does the private instance of ObjectCache in my wrapper class need to be static? Does the class itself need to be static?
General thoughts on my overall implementation?
I have not been able to find a decent blog/article on .NET ObjectCache in ASP.NET Web Applications, hence my confusion.
I'm use to using HttpContext.Current.Cache (which is static) and not care about lifetime management for the cache.
Since MemoryCache.Default is a singleton, your stateless class doesn't really need to be one. However, that's completely up to you.
You should not need locking around the ObjectCache instance.
No, and No. Making it static doesn't provide any value. Indicating it's a singleton in StructureMap makes GetInstance<>() always return the same object anyways.
The real value of wrapping ObjectCache would to be abstract the cache implementation so you can change it or mock it. Without an interface this becomes less useful.
An example implementation below...
public interface ICacheManager
{
// add, get, remove, etc
}
public class CacheManager : ICacheManager
{
private static ObjectCache _cache;
public CacheManager(ObjectCache cache)
{
_cache = cache;
}
// Add, Get, Remove methods work off _cache instance.
}
Then...
For<ICacheManager>()
.Singleton()
.Use<CacheManager>();
For<ObjectCache>()
.Use(MemoryCache.Default);
If you want to change you cache provider that is still an ObjectCache in the future, then it's easy to adjust.
I hope this helps!
Related
How would you configure the middleware to change the DBContext connection string based on a sub-domain of the income request?
It appears that the DBContext is set in the Startup... which looks too early to determine the HTTPRequest to resolve the connection string.
Well, this might not suit your needs entirely, but here's what I would do:
Create a DbContextFactory class. This DbContextFactory class can create instances of the DbContext and can pass in any string to the DbContext constructor. Then inject this factory and whenever you need an instance of the dbcontext, just ask the factory to return one for you. Of course you have to manage the lifetime of the created contexts yourself (i.e. using block).
Another option can be to create the DbContextFactory so that it holds an instance of a DbContext. When you ask for a context object from the factory, the factory creates a new one and also stores it in a private field, and subsequent calls return that same instance. Make the factory IDisposable and in its Dispose() method, dispose the context as well. This way you don't have to worry about managing lifetime (if you use a Scoped registration).
ASP.Net 5 offers an options pattern to easily convert any POCO class into a settings class. Using this I can write my settings in json and then turn them into a typed object that I can inject into my controllers. So, for example, my ConfigureServices method in Startup.cs contains the line
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
and then this gets passed into my controllers' constructors using dependency injection
public ItemsController(IOptions<AppSettings> settings) { /* do stuff */ }
One of my controllers fires up a DNN to do some of its work. To reduce the cost of starting the DNN I do that from the static class constructor. Static constructors are parameterless and so I cannot pass in the required settings object, but I could set a static IOptions<AppSettings> property on the ItemsController from my ConfigureServices method. How do I get at that? Where is the dependency injector and how do I persuade it to hand me an IOptions<AppSettings>?
I think you are looking at the problem wrong. The problem is that you have a static class and are using DI, not how to inject your dependencies into a static class (which cannot be done without resorting to a service locator or another hack).
Most DI containers have a singleton lifestyle, which allows you to share the same instance of an object across your application. Using this approach, there is no need for a static class. Eliminate the static class by replacing it with an singleton instance, and you have an avenue where you can inject dependencies into your constructor.
My application is using SQL Server 2012, EF6, MVC and Web API.
It's also using a repository and assorted files such as:
DatabaseFactory.cs
Disposable.cs
IDatabaseFactory.cs
IRepository.cs
IUnitOfWork.cs
RepositoryBase.cs
UnitOfWork.cs
We already use a service layer between our controllers and the repository
for some complicated business logic. We have no plans EVER to change to a different database and it has been pointed
out to me that the recent thinking is that EF6 is a repository so why build
another repository on top of it and why have all of the files I have above.
I am starting to think this is a sensible approach.
Does anyone know of any examples out there that implement EF6 without a
repository, with a service layer. My search on the web has revealed many
complex code examples that seem over complicated for no reason at all.
My problem is also when using a Service Layer then where do I put:
context = new EFDbContext()
In the controller, the service layer or both ? I read that I can do this with dependancy injection. I already use Unity as an IOC but I don't know how I can do this.
Entity Framework IS already a Unit of Work pattern implementation as well as a generic repository implementation (DbContext is the UoW and DbSet is the Generic Repository). And I agree that it's way overkill in most apps to engineer another UoW or Generic Repository on top of them (besides, GenericRepsitory is considered to be an anti-pattern by some).
A Service layer can act as a concrete repository, which has a lot of benefits of encapsulating data logic that is specific to your business needs. If using this, then there is little need to build a repository on top of it (unless you want to be able to change your backend service technology, say from WCF to WebApi or whatever..)
I would put all your data access in your service layer. Don't do data access in your controller. That's leaking your data layer into your UI layer, and that's just poor design. It violates many of the core SOLID concepts.
But you do NOT need an additional UnitOfWork, or other layers beyond that in most cases, unless your apps are very complex and intended to work in multiple environments...
Setting up Unity for ASP.NET MVC and WebAPI is quite easy if you install and add the Unity.Mvc* and Unity.WebAPI* Nuget packages to your project. (The * is a version number, like 3 or 4 or 5. Look for the appropriate versions for your project. Here are for example the links to the Unity.Mvc 5 package and to the Untity.WebAPI 5 package.)
The usage of these packages is explained in this blog post.
The building blocks are roughly like so:
You build a unity container and register all your dependencies there, especially the EF context:
private static IUnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType<MyContext>(new HierarchicalLifetimeManager());
container.RegisterType<IOrderService, OrderService>();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IEmailMessenger, EmailMessenger>();
// etc., etc.
return container;
}
MyContext is your derived DbContext class. Registering the context with the HierarchicalLifetimeManager is very important because it will ensure that a new context per web request will be instantiated and disposed by the container at the end of each request.
If you don't have interfaces for your services but just concrete classes you can remove the lines above that register the interfaces. If a service needs to be injected into a controller Unity will just create an instance of your concrete service class.
Once you have built the container you can register it as dependency resolver for MVC and WebAPI in Application_Start in global.asax:
protected void Application_Start()
{
var container = ...BuildContainer();
// MVC
DependencyResolver.SetResolver(
new Unity.MvcX.UnityDependencyResolver(container));
// WebAPI
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApiX.UnityDependencyResolver(container);
}
Once the DependencyResolvers are set the framework is able to instantiate controllers that take parameters in their constructor if the parameters can be resolved with the registered types. For example, you can create a CustomerController now that gets a CustomerService and an EmailMessenger injected:
public class CustomerController : Controller
{
private readonly ICustomerService _customerService;
private readonly IEmailMessenger _emailMessenger;
public CustomerController(
ICustomerService customerService,
IEmailMessenger emailMessenger)
{
_customerService = customerService;
_emailMessenger = emailMessenger;
}
// now you can interact with _customerService and _emailMessenger
// in your controller actions
}
The same applies to derived ApiControllers for WebAPI.
The services can take a dependency on the context instance to interact with Entity Framework, like so:
public class CustomerService // : ICustomerService
{
private readonly MyContext _myContext;
public CustomerService(MyContext myContext)
{
_myContext = myContext;
}
// now you can interact with _myContext in your service methods
}
When the MVC/WebAPI framework instantiates a controller it will inject the registered service instances and resolve their own dependencies as well, i.e. inject the registered context into the service constructor. All services you will inject into the controllers will receive the same context instance during a single request.
With this setup you usually don't need a context = new MyContext() nor a context.Dispose() as the IOC container will manage the context lifetime.
If you aren't using a repository then I assume you would have some place to write your logic/processing that your service operation would use. I would create a new instance of the Context in that logic/process class method and use its methods directly. Finally, dispose it off right after its use probably under a "using".
The processing method would eventually transform the returned/processed data into a data/message contract which the service returns to the controller.
Keep the data logic completely separate from Controller. Also keep the view model separate from data contract.
If you move ahead with this architecture, you are going to be tightly coupling the Entity Framework with either your service or your controller. The repository abstraction gives you a couple things:
1) You are able to easily swap out data access technologies in the future
2) You are able to mock out your data store, allowing you to easily unit test your data access code
You are wondering where to put your EF context. One of the benefits of using the Entity Framework is that all operations on it are enrolled into a transaction. You need to ensure that any data access code uses the same context to enjoy this benefit.
The design pattern that solves that problem is the Unit of Work pattern, which by the looks of things, you are already using. I strongly recommend continuing to use it. Otherwise, you will need to initialize your context in your controller, pass it to your service, which will need to pass it to any other service it interacts with.
Looking at the objects you have listed, it appears to be a considerate attempt to build this app with enterprise architectural best practices. While abstractions do introduce complexity, there is no doubting the benefit they provide.
I have a ASP.NET web site which uses domain driven design and uses repository for its database operations.
I want to know that what is pros and cons of singleton repository and static repository and simple repository class which will new on every access?
further more if anyone can compare and guide me to use which one of them I will be appreciate.
Static and singleton aren't good solution for Repository pattern. What if your application will use 2 or more repositories in the future?
IMO the best solution is to use a Dependency Injection container and inject your IRepository interface in the classes that need it.
I suggest you to read a good book about domain driven design and a good book about dependency injection (like Mark Seeman's Dependency Injection in .NET).
With singletons and static classes your application won't be scalable
You have two singleton repositories:
class Repository<TEntity> {
static Repository<TEntity> Instance { get { ... /*using sql server*/ } }
}
class Repository2<TEntity> {
static Repository2<TEntity> Instance { get { ... /*using WCF or XML or any else */ } }
}
The services using them must have a static reference to one of them or both:
class OrderService {
public void Save(Order order) { Repository<Order>.Instance.Insert(order); }
}
How can you save your order using Repository2, if the repository is statically referenced?
A better solution is using DI:
interface IRepository<TEntity> { ... }
class SqlRepository<TEntity> : IRepository<TEntity> { ....}
class OrderService {
private readonly IRepository<TEntity> _repo;
public OrderService(IRepository<TEntity> repo) { _repo = repo; }
public void Save(Order order) { repo.Insert(order); }
}
Don't use static or singleton repositories because of:
It affects testablility, you can not mock it when unit testing.
It affects extensibility, you can not make more than one concrete implementation and you can not replace behavior without re-compiling.
It affects scalability in terms of lifecycle management, insetead depend on dependency injection framework to inject the dependency and manage lifecycle.
It affects maintainability, it forces dependency upon concrete implementation instead of abstraction.
Bottom line: DONT use static or singleton repositories
instead create repository interfaces in your domain model project, and implement these interfaces in a concrete data access project, and use dependency injection framework.
Two SOLID reasons to not have singleton repository:
Consumers of repository will be coupled to repository implementation. This will negatively affect extensibility and testabiliy. This is a DIP violation. Depend on abstractions, not on concretions.
Repository implementation will have to violate SRP because it will most likely end up managing ORM session, database connection and potentially transactions. It would also have to make thread safe guarantees because it potentially can be used from multiple threads. Instead, database connection (ORM Session) should be injected into repository implementation so that consuming code can arrange multiple repository calls into transaction.
Possible solution to both problems is Constructor Injection.
I personally respectfully disagree with previous answers.
I have developed multiple websites (one with 7 millions page views per month) and never had a single problem with my static repositories.
My static repository implementation is pretty simple and only contains objects providers as properties. A single repository can contain as many providers as you need.
Then, the providers are responsible to manage database connection and transactions. Using TransactionScope, the consumer could manage the transactions or let it to the providers.
Every providers are developed using the singleton pattern.
This way, I can get my objects by simply calling this :
var myObj = MyRepository.MyProvider.GetMyObject(id);
At any time, there is only one repository and one provider of each type in every web pool of my application. Depending on how many users you have at the same time on your site, you could set more than one web pool (but most of the time one is just enough).
I don't see where my repository/providers consumers are coupled with my repository. In fact, the implementations of my providers are totally abstracted from them. Of course, all providers returned by my repository are interfaces and I could easily change the implementation of them at any time and push my new dll on the web server. If I want to create a completely new provider with the same interface, I only have to change it in ONE place: my repository.
This way, no need to add dependency injection or having to create your own ControllerFactory (for MVC procjects).
And you still have the advantage of clean code in your controllers. You will also save a lot of repository creation and destruction every time a page is requested (which normally use reflection in your ControllerFactory).
If you are looking for a scalable solution (if you really need it which most of the time is not really a problem), my way of developing repositories should never be a problem compared to dependency injection.
I got a webapp that stores a config object in ApplicationState.
This object contains the connection string to the database among other things.
Sometimes i start a async thread to do a few longer running tasks, like sending emails and updating the database.
However since this thread don't have a HttpContext i can't get at the config object.
I know this design that everything depends on HttpContext is bad, but thats too late to change now.
Looking at reflector i see that the HttpContext class just uses a static internal class to get the ApplicationState. Is there any other way to get at it?
All those internal classes in .net are really annoying.
Just pass whatever you like to your thread when you start it. Use a ParameterizedThreadStart delegate to start it instead of just a ThreadStart delegate. You could either pass it HttpContext.Current, or else bundle together the information you want your thread to have, and pass it.
If you really need access to Application State (or similar) from async handlers you should modify your HttpApplication subclass (e.g. Global.asax) to store the Application State instance (this.Application) to a static property during Application_Start:
public static HttpApplicationStateWrapper State { get; private set; }
protected void Application_Start()
{
State = new HttpApplicationStateWrapper(this.Application);
}
It would be more appropriate to use a DI framework to register this instance, but if you have one available you could probably avoid the use of Application State altogether for storing config. Further, there is a configuration framework in .NET that directly addresses this need and provides the ability to read configuration from anywhere.