Using Ninject's InRequestScope in a class library referenced by MVC - asp.net-mvc

My solution is divided as follows:
Data project - holds Entity Framework
Business Logic/Services project - contains classes that implement business logic/do other work on the data
MVC3 project
The way I have this set up is the services class does work involving entity framework. I'm using dependency injection for creating the repository wrapping Entity Framework. The problem I'm running into is that each time the repository is created via ninject, it's creating a new EF context so not all changes are being saved. Note that I have Ninject bindings in both the services project and the MVC project, and the instance I'm talking about here is when the bindings are located in the class library.
Based on the research I've done, it seems to be recommended to use InRequestScope so that way the same context gets used. However, since I'm using this in a class library instead of the MVC project/web project, does it make sense to use Ninject.Web.Common in the class library (where it goes and creates AppStart folders and everything)?
Or is there another way I should handle this?

I was misunderstanding how Ninject.Web.Common worked and I was getting confused by the auto-added NinjectWebCommon cs file that was automatically added via nuget install, making me think that it was only for the entry point project. I wasn't aware that my class library would have access to HttpContext and by getting rid of the AppStart folder that the nuget package "helpfully" added, I was able to use InRequestScope in my class library.

Related

ASP.NET Core: Correct pattern to pass DbContext to separate class libraries?

This is really a question about what would be a recommended pattern...
I use ASP.NET Core 2.0 and use dependency injection to allow my controllers and other classes to have access to a IMyDatabaseRepositor, via class constructors.
I also have several other projects in separate assemblies. I was thinking of allowing these other projects do some repository work as well. We're really talking about providing access to an existing DbContext.
Should I somehow pass the IMyDatabaseRepository instance to methods in the other project classes, or should those classes simply instantiate their own IMyDatabaseRepository (and do all their own "Startup" and connection string stuff for database and DI)?
I'm not sure if the other project classes can use the IServicesCollection somehow as well in order to get DI instances from my main ASP.NET Core web app.
Any thoughts?
Libraries should not compose object graphs, only the startup project should.
This means that in the library you simply use Constructor Injection, while in your Startup class you register all components from all libraries.

How to keep Ninject in a composition root specific project using Ninject.MVC5?

I would like to create a standalone class library project that acts as my composition root. I want to keep the concrete implementations of types out of projects where they are never intended to be used directly. This is not possible if I'm forced to construct my Ninject registrations inside my MVC web application. For example I would have to map: IAbstraction to ImplementationThatIsNotValidForDirectUseInThisLayer.
I have created the composition root specific project and added references to all my projects so that I can bind my abstractions to their corresponding concrete implementations. I have installed the Ninject.MVC5 Nuget package (and all of its dependencies) into the composition root specific project.
When I reference my composition root project in my main MVC5 web application I can set a break point on the Start and Stop methods and the code executes. This means WebActivator is correctly bootstrapping these classes at run-time.
The problem is when I hit a controller that is not parameterless I get the dreaded: "No parameterless constructor defined for this object." error message.
Why isn't Ninject being used to construct controllers and all of their dependencies? Is there some additional configuration I need to do?
I have a project reference from MyApp.WebApp to the MyApp.WebApp.CompositionRoot.Ninject project where all of my bindings are being configured.
The problem seems to occur only when the initial ASP.NET project is created from the Empty project template in Visual Studio (I'm using 2013 for what its worth) with MVC added via Nuget. If I create my ASP.NET web application using the MVC template and keep my composition root in an external class library referenced by the MVC application, the controllers are correctly constructed by Ninject. I've looked at the project created from the MVC template and the only reference that sounded potentially important that was missing was "System.Web.Abstractions. I added the reference but it did not fix the issue.
I decided to define my Ninject modules in the separate composition root only class library project, but installed the Ninject.MVC5 Nuget package into the web application. The goal of keeping the concrete implementations unavailable to the web application is maintained, but I do have to keep some references to Ninject in the MVC web application. This is a minor issue, at least this maintains my layered architecture and guarantees that a type cannot be used where it was not intended (without adding references of course!).

How to create an ASP.NET MVC class library

I want to create a class library for an MVC 4 web application. Every search I've tried has returned plenty of references that merely mention creating one, or the importance of doing so, but not specifics of how.
My first assumption was a template would be under Web in the Visual Studio New Project dialog, but no. I was unsure if I was to use the Class Library template under Windows, but did.
I want to include things like some data access (e.g., DbContext), but while Intellisense sees the System.Data.Entity namespace, there are no classes available. I guess I need some additional references, but no idea which ones. Looking at the references in my main MVC project, at lot of them are pointing to the Packages folder. I'm unsure if I should be doing the same.
In short, I'm looking for instructions on how to create a class library for MVC in Visual Studio, including the necessary references for EF, Razor and whatever else.
you used the correct template - a simple class library is all you need.
then in the MVC web project just add a reference to the class library project
Use NuGet to add references to the pieces of functionality, like EF and System.Web.MVC, that you need in your class library or libraries.
A data access project to handle persistence and a class library to hold HTML Helpers that you might want to reuse both make some sense. Razor views if you're using the RazorEngine rendering stack can also be interesting to be able to test.
You are right to use the Class Library template in visual studio for your needs. You can add all of the references you need through NuGet (such as Razor, EF, and so on) and by Right clicking on references in the Solution Explorer and picking and choosing what you need.
Remember when using multiple projects that you add references between projects too! (for example your Web App project needs to know about your Data Repository Project)

Decoupling Microsoft.AspNet.Identity.*

I am working in Visual Studio 2013 RC and am testing Forms Authentication using new Microsoft.AspNet.Identity.* packages.
I would to integrate these concepts (Users, Roles, etc, etc) but want to use my own domain models (POCOs) which are in different assembly. I also don't want to create a dependency on Microsoft.AspNet.Identity.* dlls.
Is that even possible?
I found this article which says it is not, but the article is written based on Preview not RC versions of identity packages.
I have updated my sample project which you can find here: Identity RC1 sample
It now implements an entity framework model, it still require a reference to the Microsoft.AspNet.Identity.EntityFramework as I didn't want to reimplement all the Store classes also. But the sample shows how you can use your own POCO classes for the model.
If you want to completely remove the dependency on Microsoft.AspNet.Identity.EntityFramework from your model assembly you need to implement an class implementing the IIdentityStore interface which has properties of the following interfaces:
IUserLoginStore
IRoleStore
IUserSecretStore
ITokenStore
IUserClaimStore
IUserManagementStore
IUserStore
The IIdentityStore class should be in an assembly separate from your model assembly, with a reference to your model assembly. The IIdentityStore assembly would be dependent on ASP.Net Identity core.
Your custom implementation of IIdentityStore would need to somwhow be able to convert to and from your POCO classes to ASP.Net Identity interfaces such as IUser, IUserSecret etc.
Seems to me to be a lot of work for little gain, if you are using EF for your stores anyway.
Taking a dependency on the AspNet.Identity.Core assembly and have some of your POCO classes implementing one tiny interface each, seems a lot simpler to me.
Yes this is a fully supported scenario, basically you will want to use exclude using the Microsoft.AspNet.Identity.EntityFramework dll which has the default EF implementation, but you should be able to reuse the Manager classes and just implement your own custom Stores using your own POCOs which the manager will use just fine via the interface. For RTM its been streamlined and simplified a bit more, I believe the RC version was not quite as streamlined yet.
Updated You can get early access to the RTM bits here: MyGet
Just in case. Maybe I can help someone.
exorcising entity framework from asp.net.Identity
I'd created separate project(class library), then add ref to asp.identity.core,
then I'd implemented my UserStore class there, and feed it my Identity config in Web project.
It works fine in project with complex n-tier architecture.

MVC with 3Tier Architecture, Entity Framework and DependencyInjection [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
DAL -> BLL <- GUI + composition root. How to setup DI-bindings?
I'm defining a new solution and i've created some projects:
WebUI
Domain (contains my entities)
BusinessLayer (contains my business rules)
DataAccessLayer (contains my Abstract and Concrete implementations of my repositories)
Every project has a reference for my Domain.
In every example i see in Internet, the dependency injection (ninject) is defined in WebUI, but i cannot do that because it'll require me to add a reference for my DataAccessLayer.
If i move the binding association to the BusinessLayer then my WebUI will not become database agnostic because the bindings are hardcoded in my BusinessLayer.
Please give your opinion (even in the architecture), and why i'm having decision implementation problems?
thank U ALL
You would normally configure the container in the application project. In your case the ASP.NET MVC application. This configuration will need to reference all assemblies in your solution. This is normally not a problem. Just don't use the DAL library from the rest of the web application.
If that is a problem for you, create a special Bootstrapper project that references all projects and configures the container. Then call that project from within your Application_Start event.
It's ok if you have references to your data access layer in web app, so long as you don't actually reference them in your code (other than in your ninject configuration). The reason is that Ninject is configured in code, thus to change your configuration you have to change the code.
If you want a purely file based configured approach, then you would need to use a different Container, or develop a file based configuration based on Ninject.
So long as your CODE is database agnostic, all you have to do is change your ninject code and modify the references and you're good to go, you don't have to change your app.

Resources