How can I inject ApplicationDbContext in another assembly? - dependency-injection

I am trying to move some ViewComponents from the main web application to a separate class library (ASP.NET Core 1.1) which does NOT have the Entity Framework models or Identity stuff.
However, those view models depend on ApplicationDbContext to access the data (not all of what is available, just specific things). It kind of partially defeats the purpose of reusability (in other projects) if I have to leave the view component in the main web application.

You can move ApplicationDbContext to a separate project.
Let say ApplicationDbContext locates in Data project, and ViewComponents locate in Common project.
Web project references both projects. Common project references Data project.

Related

Using Asp.Net Core dependency injection to inject classes to other projects

I have an ASP.Net Core project responsible for handling all web requests, and I have another project responsible for reading/writing from and into the database (Entity framework Core project).
and of course another projects for different things but let's now imagine just we have only the previous two projects for the simplicity.
Is it possible some how to use ASP.Net Core dependency injection to inject classes into another projects (other projects which are library classes and not ASP.Net Core projects)? for example injecting DbContext to my Entity framework project?
It may be that what you are thinking of doing is futile? If you are running inside an Asp.Net application, then all your code is probably called from a Controller, and the Controller can get all the dependencies you need, and pass them through:
public class MyController : Controller
{
readonly MyComponent myComponent;
public MyController(MyDbContext dbctx)
{
myComponent= new MyComponent(dbctx);
}
// ...etc...
}
But is one of your other projects a ConsoleApp or Service that runs outside the Asp.Net application? Then the question is, can I reference Asp.Net.Core to use DI outside of Asp.Net?
I suspect the answer is 'probably-yes', and your starting point would be to copy MS's builder code on github.
But that would beg the question, of why choose the Asp.Net DI over all the existing DI containers out there? Castle.Windsor, AutoFac, StructureMap, Ninject have all done the job well for years.

Using Ninject's InRequestScope in a class library referenced by 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.

Separate solution into different projects

I'm currently learning ASP.Net MVC; I'm using Visual Studio Express 2012 with MVC4 (which is the last version) and I'm totally new to this stuff. My goal is to rewrite a huge web application to MVC, so I was told to separate my main solution into 3 projects using the code-first method:
The core (models and controllers I guess)
The UI (views, scripts, and Content)
And the Database (Entity Framework 5.0 will be used)
I'm quite familiar with MVC, but not separating stuff into different projects. Now I'm a bit lost, I don't have a clue on how to do that, which should reference who, where, how, etc.
Your solution could be structured this way:
UI - ASP.NET MVC application project containing the controllers, views, view models, mapping logic between your domain models and view models, scripts, styles, ...
DAL (EF 5.0, EF autogenerated domain models, Data Contexts, ...) everything that is specific to the data retrieval
The UI layer will then reference the DAL layer.
Some people might also opt to externalize the controllers, view models and mapping logic into a third layer which in turn will reference the DAL layer. The UI layer in this case will reference both other layers.
There are tutorials available on here: http://www.asp.net/mvc
It really helped me out to get the basics of MVC, but be aware - sometimes there are parts missing in the video's, but you can find the code which isn't provided easily elsewhere.
Good luck :)
The tutorials are used to show code first.
create an empty solution using the Visual Studio Blank Solution template
add a solution folder (folder name will be your project name)
then right click that folder and select add project then select "class library" (for The c# classes domain logic)
same again right click the folder and select add project then select asp.net mvc3 template
then same way you create the test template as a new project.
For more information you can follow this book http://www.apress.com/9781430234043

Layering an ASP.NET MVC Web Application

When I develop a WinForms or WebForms app, I create a solution and add multiple projects. The BOL project is a class library for business objects, there's a SQL and a DAL project for ADO.NET related stuff, I have a Utilities project which contains classes for stuff like validation and whatnot. Now the presentation layer which I usually call the GUI contains the forms. The forms work directly with the BOL, which connects to the SQL which connects to the DAL, etc...
I'm sure you all know this already so here's where I get confused. In working with MVC, projects I see all contain this type of functionality but are all in one project, just separated into folders. I looked at the Nerd Dinner application and even that is all in the one project. The end result is a single DLL to handle it all. Is this a good idea, or do you guys separate the pieces into different projects? Usually one DLL has to go through another DLL before it can reach the data access DLL type of thing. Maybe I'm just confused on the whole concept.
You can always seperate this logical layers into seperate physical layers (projects). You can create a seperate project for your Entities, one for your Data Access code etc..
Here is the structure i did for one of my receny project
1) UI : The standard MVC Project with UI related stuff. Controllers and Views and Relevant CSS stuff & Scripts.
2) Entities : The class library Project. My Business entities are here. These are just POCO's which represent my domain modal ( I use this for the CodeFirst Database generation).
3) Data Access : The class library Project. I have my Data Access code here. Repositary, Interfaces and my DBContext class as well.
4) Test : My Unit Tests are in this project.
UI Project has a reference to my Entities and My Data Access Project.
Data Access Project has a reference to my Entities because my Repositary method returns objects.
I have few ViewModel classes also inside my UI project ViewModels folder. I use this for some screens where i have to show data from multiple domain objects. I have a mapping/service class which maps the domain object to view model object. If your project is bifg, you may keep this as a serperate project under the same solution.
The solution looks like this. (This is an open source project i am working on)

DAL -> BLL <- GUI + composition root. How to setup DI-bindings?

I have made a three-layer application with refrences going as described in this answer:
DAL with Repositories -> BLL with services and IRepository <- Asp.net mvc-app
To get this running with dependency injection I see a few options:
1. Add a reference to DAL from the web-app to be able to setup bindings on application start.
2. Use a container with xml-configuration
(3. Use reflection to load the dal-assembly and find types)
Option 1. is easy and also makes the DAL.dll be copied to bin but then I suddenly reintroduce the reference I worked so hard to get rid of. The repositories can now be accessed directly. Option 2 and 3 seems unnecessarily complex.
Is there no other way?
Split up the ASP.NET MVC application in two:
One part is your original ASP.NET MVC application, but without any logic whatsover. Just keep the Composition Root and your Views (.aspx, etc.) in this project. Since this is the Composition Root, you can have references to all your other projects. However, since all logic would have been extracted, this is now a Humble Object, so it's okay to have all the references at this level.
Extract all the logic (Controllers, etc.) into an Application Model project, which would just be a normal library project (.dll) that references the ASP.NET MVC binaries. This project would need to reference the BLL to get at the interfaces, but that's okay. However, both the Application Model and the BLL are effectively shielded from the DAL.
The resulting layering would look like this:
ASP.NET MVC application
Application Model
BLL
DAL
Mark Seemann's answer gave me the idea for this variant:
DAL with Repositories -> BLL with services and IRepository <- Asp.net mvc-app
^------------------------^--------- Composition Root <-------ยด
This is meant to illustrate that instead of letting the Web project reference the DAL it references a separate Composition Root-project that references both DAL and BLL. The composition-root-project has a single class with one method that define the bindings. It gives these additional benefits:
Only three layers. Four layers would be a tough sell in the team.
Loose coupling is ensured. It is not possible to access the DAL from view-code.
Better tool support. Controllers remain at the standard location so "Add Controller" is accessible on the context-menu and missing views are highlighted in the controller-code. Also there is no need to configure or write a custom controller factory.
I don't see any big drawbacks.
Just go with Option 1.
Just because you have a reference to the assembly doesn't mean your breaking the SoC.
The Web Project still knows nothing about the underlying implementations, only the interface.
The Web Project is the "aggregator" of the below layers therefore it makes sense it should know about them in order to configure them.
I split the MVC project in two roughly as described in Mark Seemans Answer.
The MVCApplication is a humble object and requires references to everything, but doesn't have any of the MVC code, apart from global.asax (which it needs) and web.config (which it seems to want).
The MvcUI project only references interfaces and uses dependency injection.
If you put both the projects (.csproj files) in the same directory then the Content, Controllers, Models, Scripts and Views folders are all actually in the same place, so all the tooling works.
The picture of the solution below shows the idea.
The directory structure looks something like this
And you end up with a Dependency graph like this
Recently i was following the same thing and figured about the MEF (Managed Extensibility Framework). With the help of MEF and reflection you can get rid of that DAL/Unit of work reference from your composition root and you don't need to have 2 mvc projects as discussed above.

Resources