Use Entity Framework Code First with ASP.NET and Unity Ioc - asp.net-mvc

I got ASP.NET MVC application and I'm using EF code first and Unity dependency injector.
I've implemented the DDD design and have repositories and services which interact with my POCO objects.
My problem is that I'm getting EF related problems - such as the connection was closed, the entities changed or not tracked and so on. As I've understand from researches in Google, it related to the way that I should configure Unity.
I've understood that I need to put it as per request instance, but as I see there's no built-in strategy in Unity nor in the Unity.Mvc3 package.
I've tried to write my own strategy, which solved many problems but I do stuck with the problem that sometimes I get "connection closed".
My HttpContextLifetimeManager.cs
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
public override object GetValue()
{
return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
}
public void Dispose()
{
RemoveValue();
}
}
And inside DependencyConfig.cs (MVC 4 App_Start) I'm registering it using:
container.RegisterInstance<MyDbContext>(new MyDbContext(), new HttpContextLifetimeManager<DependencyConfig>());
Can you recommend me an implementation that works/help me fix mine/forward me to an article or a tutorial that can help me solve that problem?
Thanks a lot.

App_Start method is only called once when the first request comes for the application.
Called when the first resource (such as a page) in an ASP.NET application is requested.
The Application_Start method is called only one time during the life cycle of an application.
See MSDN
Therefore you are creating the one context for all requests. Then after sometimes it may be disposed. And it's not a good practice to keep one DbContext for all the requests (memory issues etc..).
So you can try putting that code in the Application_BeginRequest .

Related

Using Dependency Injection without any DI Library

I am new to Repository and DI and trying to implement in my MVC 5 project.
I implemented Constructor Injection where in my controller has a constructor like this:
IBook _ibook;
public Test(IBook ibook)
{
_ibook = ibook;
}
Without any DI library, it throws an error: There is no empty constructor.
To avoid this, I added one more constructor as below:
public Test ():this(new Book())
{
}
Since I am new to DI, I don't want to risk my project by using DI library which can later throw some error that I may not be able to resolve.
I want to know what issues I might encounter if I am not using DI library.
In case it is recommended, which DI library is good for beginners? I have seen few videos of NInject and Unity.
It is a good idea to delay any decision to use some kind of tool or library until the last responsible moment. With a good design you can add a DI library later on. This means that you practice Pure DI.
The preferred interception point in MVC is the IControllerFactory abstraction since it allows you to intercept the creation of MVC controllers, and doing so prevents you from having to implement a second constructor (which is an anti-pattern). Although it is possible to use IDependencyResolver, the use of that abstraction is much less convenient because it is also called by MVC to resolve things you are typically not interested in.
A custom IControllerFactory that will act as your Composition Root can be implemented as follows:
public sealed class CompositionRoot : DefaultControllerFactory
{
private static string connectionString =
ConfigurationManager.ConnectionStrings["app"].ConnectionString;
private static Func<BooksContext> bookContextProvider = GetCurrentBooksContext;
private static IBookRepository bookRepo = new BookRepository(bookContextProvider);
private static IOrderBookHandler orderBookHandler = new OrderBookHandler(bookRepo);
protected override IController GetControllerInstance(RequestContext _, Type type) {
// Unfortunately, because of MVC's design, controllers are not stateless, and
// you will have to create them per request.
if (type == typeof(OrderBookController))
return new HomeController(orderBookHandler);
if (type == typeof(BooksController))
return new BooksController(bookRepo);
// [other controllers here]
return base.GetControllerInstance(_, type);
}
private static BooksContext GetCurrentBooksContext() {
return GetRequestItem<BooksContext>(() => new BooksContext(connectionString));
}
private static T GetRequestItem<T>(Func<T> valueFactory) where T : class {
var context = HttpContext.Current;
if (context == null) throw new InvalidOperationException("No web request.");
var val = (T)context.Items[typeof(T).Name];
if (val == null) context.Items[typeof(T).Name] = val = valueFactory();
return val;
}
}
Your new controller factory can be hooked into MVC as follows:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start() {
ControllerBuilder.Current.SetControllerFactory(new CompositionRoot());
// the usual stuff here
}
}
When you practice Pure DI, you will typically see your Composition Root consist of a big list of if statements. One statement per root object in your application.
Starting off with Pure DI has some interesting advantages. The most prominent one is compile time support, because this is something you will lose immediately when you start using a DI library. Some libraries try minimize this loss by allowing you to verify your configuration in a way that the compiler would do; but this verification is done at runtime and the feedback cycle is never as short as that which the compiler can give you.
Please don't be tempted to simplify development by implementing some mechanism that allows creating types using reflection, because in doing so you are building your own DI library. There are many downsides to this, e.g. you lose compile time support while not getting back any of the benefits that an existing DI library can give you.
When your Composition Root is starting to get hard to maintain, that is the moment you should consider switching from Pure DI to a DI library.
Do note that in my example Composition Root, all application components (except for the controllers) are defined as singleton. Singleton means that the application will only have one instance of each component. This design needs your components to be stateless (and thus thread-safe), anything that has state (such as the BooksContext) should not be injected through the constructor. In the example I used a Func<T> as the provider of the BooksContext which is stored per request.
Making your object graphs singletons has many interesting advantages. For instance, it prevents you from making common configuration errors such as Captive Dependencies and it forces you into a more SOLID design. And besides, some DI libraries are very slow, and making everything a singleton might prevent performance problems when switching to a DI library later on. On the other hand, the downside of this design is that everybody on the team should understand that all components must be stateless. Storing state in components will cause needless grief and aggravation. My experience is that stateful components are much easier to detect than most DI configuration errors. I have also noticed that having singleton components is something that feels natural to most developers, especially those who aren't experienced with DI. For a detailed discussion on the two composition models to choose from and their downsides and advantages, take a look at this serie of blog posts.
Note that in the example I manually implemented a per-request lifestyle for the BooksContext. Although all DI libraries have out-of-the-box support for scoped lifestyles such as per-request lifestyles, I would argue against using those scoped lifestyles (except perhaps when the library guarantees to throw an exception instead of failing silently). Most libraries do not warn you when you resolve a scoped instance outside the context of an active scope (for instance resolving a per-request instance on a background thread). Some containers will return you a singleton instance, others return you a new instance each time you ask. This is really troublesome because it hides bugs and can cause you many hours trying to debug your application (I speak from experience here).
The simplest and sanest solution is to use Pure DI. With ASP.NET MVC, this is most easily done by deriving from DefaultControllerFactory and overriding GetControllerInstance:
protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType)
{
if (controllerType == typeof(Test))
return new Test(new Book());
return base.GetControllerInstance(requestContext, controllerType);
}
Then register your new Controller Factory in your Global.asax like this:
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
Unfortunately, much documentation will tell you to use IDependencyResolver, or Bastard Injection to deal with Dependency Injection, but these will not make your code more maintainable.
There are lots of more details, including examples of how to properly use Dependency Injection with ASP.NET MVC, in my book.
If you're only interested in Dependency Injection to achieve some level of abstraction, you're definitely not required to use any IoC framework.
If you don't care about scope, lifetime and nested dependencies, you may end up with something as primitive as this:
internal class MyBasicResolver : IDependencyResolver
{
private readonly Dictionary<Type, Type> _services = new Dictionary<Type, Type>()
{
{ typeof(IBook), typeof(Book) }
// more services registrations
};
public object GetService(Type serviceType)
{
return _services.ContainsKey(serviceType) ? Activator.CreateInstance(_services[serviceType]) : null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
yield return GetService(serviceType);
}
}
Then register it as the current Dependency Resolver for MVC:
DependencyResolver.SetResolver(new MyBasicResolver());
See MSDN
Ninject and unity provide object container, which contains object wich you have register at startup of the application,
But why you need to use di, Di states that two objects should not depend upon its concreation it should depend upon its abstraction, so if suppose in futere you need to replace Book class to eBook, here both the class has same function but it has diffrunt concreation at that time you need to just your di configuration you dont need to recode the controller for eBook.
I am using unity di in my most projects I didt face any issue which I cant resolve its easy and make practice to use that, dont be afraid for that.

Where does an MVC Controller get it's database context at run time

Given this code:
namespace Eisk.Controllers
{
public class EmployeesController : Controller
{
DatabaseContext _dbContext;
public EmployeesController(DatabaseContext databaseContext)
{
_dbContext = databaseContext;
}
public ViewResult Index()
{
var employees = _dbContext.EmployeeRepository;
return View(employees.ToArray());
}
Note that the constructor doesn't new up a database.
When accessed from a unit test I can inject a databaseContext and the controller will use that for the duration of the test. What I can't figure out is where this code is getting the database context it's using at run time. If I could find that out I might be able to figure out how to circumvent that behavior and have it use a mocked/in memory DB instead.
More explanation:
I don't have access to a legacy database for this application right now so I'm trying to Mock up an in memory data source that gets filled from xml files. That's why I need to be able to circumvent the default database context creation.
More Information:
Thanks for all the help so far you wonderful people you.
Steven seems to have directed me down the correct path.
In the Global.asax file is this call:
DependencyInjectorInitializer.Init();
Following that through the code I get to:
public static void Initialize()
{
_container = new UnityContainerFactory().CreateConfiguredContainer();
var serviceLocator = new UnityServiceLocator(_container);
ServiceLocator.SetLocatorProvider(() => serviceLocator);
DependencyResolver.SetResolver(new UnityDependencyResolver(_container));
}
At least that gets me headed in the right direction. Now I have to figure out how Unity is going about creating the context so I can do my intervention.
Let me plug the EISK MVC Employee Info Starter Kit here. It's a well thought out system developed by Mohammad Ashraful Alam Et al. that includes a well fledged example of how many of the new technologies fit together. MVC 5, Entity Framework 6, Unity, Authentication, OpenAuth, DI, Moq, and a couple of other things. Can be used as a template, general learning, or training.
Employee Info Starter Kit
With the default configuration of ASP.NET MVC, a controller should have a default constructor (i.e. a public constructor with no parameters). If not ASP.NET MVC will throw the following exception:
Type 'Eisk.Controllers.EmployeesController' does not have a default
constructor
If this however works, this means that you (or another developer) overwrote the default configuration by either using a custom IControllerFactory or custom IDependencyResolver. Most developers do this by using an open source Dependency Injection library (such as Simple Injector, Autofac or Castle Windsor). If you pull in the NuGet MVC integration packages for such library, it will usually do this configuration for you. So somebody on your team might have done this for you.
My advice is: talk to your team and ask them how they did this and which container they used and where you can find the configuration for that.

Dynamo IoC and Mvc

I'm trying out Dynamo IoC with the web extensions for Mvc, and I see they've done a great work creating a custom HttpApplication to derive your Global.asax from. However it seems I'm missing something.
I want to accomplish DI in my controllers, but I'm stuck with the usual "The controller must have a parameterless constructor" problem.
This is what I do in my global.asax (which derives from DynamoMvcAndWebApiApplication):
protected override void RegisterDependencies(Dynamo.Ioc.IIocContainer container)
{
container.Register<ILogger, FakeLogger>();
}
Then my controller:
public class HomeController : Controller
{
private readonly ILogger logger;
public HomeController(ILogger logger)
{
this.logger = logger;
}
public ActionResult Index()
{
logger.Log("test");
return View();
}
}
This gets me the "no parameterless constructor error". I thought the web extensions of Dynamo already took care of whatever was required to make DI work.
If I add a parameterless constructor it gets called, but then my ILogger will be null, and I'll get a NullReferenceException in my action method.
I thought about having to implement a ControllerFactory but I also thought that if it was mandatory they would have provided it along with all other stuff for MVC, so I think that I am misusing what is provided.
I'd like to know if anyone knows how to make DI work in this scenario. Thanks.
My best guess is that it is because you don't register the HomeController when registering the dependencies.
According to your example you don't.
I agree with MartinF. If you want your HomeController's dependencies to be resolved, you need to instantiate it by resolving it from your Dynamo container. Granted, I'm not seeing your resolve code, but I'm just guessing that's what's going on. I don't think it's a matter of "Dynamo doesn't fully integrate with MVC". Depending on how the container works, you may not even need to explicitly register HomeController with the container before trying to resolve it, but you DO need to ask the container to resolve it for you so that it may satisfy the dependencies. Just my guess based on the usage of other containers.
After a long digging and experimenting, it just seems that Dynamo doesn't fully integrate with MVC. I tried Ninject integration with MVC and it works fine, out of the box.
My guess is that Dynamo is just "not there yet", I'll keep checking on its updates in the future.

Using Ninject with Asp.NET Web API Beta ApiController

I'm stuck. I was using the method outlined here for wcf web api p6 Ninject working with WCF Web API Preview 5, however things are quite a bit different with the mvc implementation in the beta. There is a good article here http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver that talks about building your own custom dependency resolver, however i would like to use the same implementation i'm using for my mvc view controllers...e.g. Ninject. I've tried a few things based on the IoC Unity example in the article too, but nothing has panned out yet. Any help pointing me in the right direction would be much appreciated. I'm going to keep digging on my own as well. Thanks in advance!
Here's where I'm at. I was using WebActivator to bootstrap the code but I've since dropped it to the Application_Start() just to take one more thing out of the equation.
protected void Application_Start()
{
var kernel = new StandardKernel(new MyNinjectModule());
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
And am receiving the following error:
The type Ninject.Web.Mvc.NinjectDependencyResolver does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.Parameter name: commonServiceLocator
Found the solution
Perhaps there is/will be a more elegant way but this is now working for me. I'm also adding my custom message handler here as well.
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart.ApiBootstrapper), "Start")]
namespace MyApp.AppStart
{
public class ApiBootstrapper
{
public static void Start()
{
var kernel = new StandardKernel(new MyNinjectModule());
var resolver = new NinjectDependencyResolver(kernel);
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(resolver.GetService, resolver.GetServices);
GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiAuthHandler());
}
}
}
I never used the WebAPI but since the semantic of the IDependencyResolver is exactly the same as the one from MVC3 you should be able to use the same implementation: https://github.com/ninject/ninject.web.mvc/blob/master/mvc3/src/Ninject.Web.Mvc/NinjectDependencyResolver.cs
Update:
The Ninject.Web.WebAPi extension adds support for ApiControllers
I found the answer and updated my question above with the solution. The solution itself was more or less present in the Using the Web API Dependency Resolver article, i just had to keep tweaking for ninject. Both answers helped me quickly narrow this down so thanks to #Remo and #James.
May sound silly but have you made sure you have a reference to the CommonServiceLocator / CommonServiceLocator.NinjectAdapter nuget package or associated assemblies. Your NinjectDependencyResolver may not be able to resolve the reference to IServiceLocator.
The same code will work for both MVC and the WebApi, however because the WebApi was inspired by MVC and the MVC assemblies do not have to be referenced in order to use WebApi (or vise versa), there is a fair amount of duplication of code between the two frameworks. If you want to use MVC you're dependencies will come from System.Web.Mvc, if you want to use WebApi you'll use System.Web.Http. If you want to use both you'll have to differentiate in your code which to use when, using a more explicit namespace resolution.
In your case your problem is that MVC came first and the NinjectDependancyResolver class inherits from System.Web.Mvc.IDependencyResolver. You'll want to create an exact duplicate of the NinjectDependancyResolver class and instead inherit from System.Web.Http.IDependencyResolver instead. Use THIS class to setup your IoC and you'll be good to go.
I found a nice solution here.
It's pretty easy if you're already using the Ninject CommonServiceLocator / Bootstrapper:
private static IKernel CreateKernel() {
var kernel = new StandardKernel();
RegisterServices(kernel);
GlobalConfiguration.Configuration.ServiceResolver
.SetResolver(new NinjectServiceLocator(kernel));
return kernel;
}

How can I implement NHibernate session per request without a dependency on NHibernate?

I've raised this question before but am still struggling to find an example that I can get my head around (please don't just tell me to look at the S#arp Architecture project without at least some directions).
So far I have achieved near persistance ignorance in my web project. My repository classes (in my data project) take an ISession in the constructor:
public class ProductRepository : IProductRepository
{
private ISession _session;
public ProductRepository(ISession session) {
_session = session;
}
In my global.asax I expose the current session and am creating and disposing session on beginrequest and endrequest (this is where I have the dependency on NHibernate):
public static ISessionFactory SessionFactory = CreateSessionFactory();
private static ISessionFactory CreateSessionFactory() {
return new Configuration()
.Configure()
.BuildSessionFactory();
}
protected MvcApplication() {
BeginRequest += delegate {
CurrentSessionContext.Bind(SessionFactory.OpenSession());
};
EndRequest += delegate {
CurrentSessionContext.Unbind(SessionFactory).Dispose();
};
}
And finally my StructureMap registry:
public AppRegistry() {
For<ISession>().TheDefault
.Is.ConstructedBy(x => MvcApplication.SessionFactory.GetCurrentSession());
For<IProductRepository>().Use<ProductRepository>();
}
It would seem I need my own generic implementations of ISession and ISessionFactory that I can use in my web project and inject into my repositories?
So just to clarify - I am using NHibernate in my repository layer and want to use a session-per-(http)request. Therefore I am injecting an ISession into my repository constructors (using structuremap). Currently to create and dispose the sessions in each request I have had to reference NHibernate from my web project. This is the dependency I would like to remove.
Thanks,
Ben
Why don't you create an IHttpModule and perform your creation and disposing there (probably in the Begin_Request and End_Request events), but put your IHttpModule inside the project that has your NHibernate dependency. eg.
namespace MyWebApp.Repository.NHibernateImpl
{
public class NHibernateModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Context_BeginRequest);
context.EndRequest += new EventHandler(Context_EndRequest);
}
private void Context_BeginRequest(object sender, EventArgs e)
{
// Create your ISession
}
private void Context_EndRequest(object sender, EventArgs e)
{
// Close/Dispose your ISession
}
public void Dispose()
{
// Perhaps dispose of your ISessionFactory here
}
}
}
There is maybe a better way, I'm interested to know this as well, so any alternative suggestions?
In my opinion, you should embrace the ISession and work with it directly. The problem with many session-per-request implementations is that they delay committing database changes until the end of the HTTP request. If the transaction fails, all you can do at that point is direct the user to a generic error page. It's much better to manage the transaction on the page so that you can catch and handle errors more effectively. If you take this route then you need to access the ISession or a wrapper to control the transaction.
Also, at some point your application will probably need to use properties or methods exposed by ISession, especially Merge and Load.
Thanks for everyone's help so far. A bit more research led me to the NHibernate Burrow project.
From the project FAQ (http://nhforge.org/wikis/burrow/faq.aspx):
Burrow is a light weight middleware developed to support .Net applications using NHibernate (maybe also referred as NH in this article) as ORM framework. Using Asp.net with NHibernate could be a challenge because of the fact that NHibernate is a stateful environment while Asp.net is a stateless framework. Burrow can help solve this conflict by providing advanced and smart session/transaction management and other facilitates.
I had to jump through a few hoops to get it working in my project. Since the current release uses an old version of NHibernate I had to download the latest source from the trunk, open in VS, add references to latest version of NHibernate and recompile (fortunately no errors).
I tested NHibernate Burrow in a number of ways.
1) Continue injecting ISession into my repositories
To do this, I had to add references to NHibernate, NHibernate.Burrow and NHibernate.Burrow.WebUtil to my MVC project.
In web.config I had to set up Burrow (see http://nhforge.org/wikis/burrow/get-started.aspx) and then in my StructureMap registry add the following:
For<ISession>()
.TheDefault.Is
.ConstructedBy(x => new NHibernate.Burrow.BurrowFramework().GetSession());
I like this approach as it means my repositories (or controllers) are not coupled with Burrow. I don't really like the fact that I have to reference these three assemblies in my web project but at least I lose the code for managing the session - this is all handled by Burrow.
2) The second approach would be to set ISession in my repository constructors like so:
public ProductRepository() :
this(new BurrowFramework().GetSession()) { }
public ProductRepository(ISession session) {
_session = session;
}
I can still override ISession making my repositories testable. I then have a direct dependency on Burrow but perhaps this isn't such a bad thing?
On the plus side, the only assembly I need to reference from my web project is NHibernate.Burrow.WebUtils.
Interested to see which of the two people would go for and why.

Resources