Separate ASP.NET Project references when using DI (Autofac) and Identity - asp.net

I want to separate my ASP. NET MVC 5 + WebApi2 solution into separate logical projects, so (in my head) I have:
Data.csproj
references EF6 and handles Code First migrations
Models.csproj
references Automapper
refrences Data (above)
Services.csproj
references Models (above)
Web.csproj
references autofac
references services above
But I can't get my real project to look like that because
Identity sprinkles the model and EF references all over my Web.csproj
When I configure Autofac in Web.csproj and try to register my DbContexts and whatever other dependencies are in my other projects, I will need access to the concrete types, so Web will need to reference all other projects as the DI is setup in Web?
This is a brand new project auto-generated by the ASP .NET template. Thanks.

Generally, you avoid getting your Entity-Framework pollution into your web code by not referencing your data-models in your web project.
If you put interfaces for the models in a separate infrastructure project, for example, you won't have that problem any more. Your 'services' can return abstract types with no dependency on EF and coupling is reduced.
Personally, I like to get around this problem wither with a separate project that is responsible for factory code or (even better IMO) giving each project responsibility for constructing its own objects. Having the factory code in the same place further reduces coupling and can make refactoring easier.
One more thing...
If this is a new project, why do you even need a DI container. You could always use poor man's dependency injection and refactor later when you have a better idea of your needs. They are often overused or used as a crutch to hide overly complex lasagna code. It is an incredibly useful and powerful technology, but most of the benefit in terns of flexibility can also be realised through well designed factories and builders. These can have the additional benefit of increased readability.

Related

Advice on refactoring Business/Data Logic in preparation for migrating WebForms to MVC

I'm looking some advice on to a strategy for migrating from Asp.Net WebForms to MVC. I currently have a solution of approx 60 projects in the following format:
Solution
ProjectA.DataModel
ProjectA.Business
ProjectA.Web
ProjectB.DataModel
ProjectB.Business
ProjectB.Web
Framework.Core
Framework.Common
…etc
All data models are Entity Framework 6 using database first (.edmx) and T4 templates. Data access code is mixed between both the Business and Web (WebForms) projects. The code base has grown organically initially from a sole developer through to a small team which explains some of the bad practice in terms of SOC however we want to try take this opportunity to rectify this.
I want to start moving towards a full MVC solution and feel the first thing to do is ensure any data access logic currently residing in the Web projects is pushed to the Business layer to get Separation of Concerns. Researching into a best practice for this has taken me towards the Unit of Work and Repository patterns however further reading seems to be suggesting this is overkill.
What would be the best approach to refactoring my Business and Data Layers with the current Web Forms model in readiness for MVC. Secondly is an accepted approach for migration to MVC to bring in Views to the existing WebForms solution to create a Hybrid or to create a new MVC project, reference my existing BAL and DAL and start building the application UI from scratch?
In regards to Entity Framework, everything appears to be moving towards a CodeFirst approach. Is this something we need to be planning for if we want to go forward with a best practice approach?
We are currently a very small team and want to try make best possible re-use of our existing projects and refactor as much as possible to get into a position of beginning to move towards MVC.
Any thoughts on how I can begin to approach this is appreciated.
Thanks
Nasty app you have there. Anywas, first thing to rembmer is that MVC is a UI pattern. So in a properly designed app the swtich from WebForms to Mvc would mean just change the UI layer.
I want to start moving towards a full MVC solution and feel the first thing to do is ensure any data access logic currently residing in the Web projects is pushed to the Business layer to get Separation of Concerns
No! Data access logic should be in the DAL (hint: it's an acronym), not BL, not UI. Persistence Only. BL and UI would ask the DAL to save/retrieve their objects via Repository. And btw, EF deals with db only. Don't make the mistake to build your business objects on top of Ef Entities. One models business concept and behaviour, the other model database access. They're usually not compatible. When dealing with anything but persistence, ignore that you have a db or an ORM.
Researching into a best practice for this has taken me towards the Unit of Work and Repository patterns however further reading seems to be suggesting this is overkill.
It's overkill ONLY if you a have a very simple app that you don't care about maintaining it. I know is hard to believe but probably over 80%(more or less random number) of devs still don't understand how to properly implement the Repository pattern that's why it becomes useless for them. In a nutshell, the repo uses the EF but it's not built on top of it. The repo 'transforms' business/ui objects to EF entities and vice versa.
The repo interface should never expose IQueryable or the fact that you're using a db in the first place. So, no generic repositories and no exposing of EF entities. Also, the Bl/UI shouldn't create queries (it would mean they know how the data is stored - a DAL implementation detail), that's the repository's job. THe higher layers just tell the repository what they want, never how to do it.
Secondly is an accepted approach for migration to MVC to bring in Views to the existing WebForms solution to create a Hybrid or to create a new MVC project, reference my existing BAL and DAL and start building the application UI from scratch?
Although you can mix WebForms and Mvc in the same project, it's better not to do it (less headaches). Start the mvc app from scratch then port the web forms pages to it.

What is proper abstraction using Entity Framework in webforms

I am trying to figure out a good way to architect my solution. I know that I am going to be using the following technologies, Asp.Net Webforms, and Entity Framework 4.1. My EF model is based on an existing database. I'm planning to use the EF DbContext generator to build my context and entities. And this is the point where things get a little tricky for me.
I want to have proper separation of concerns, providing for better testability and allowing me to separate my business logic from my DAL. I have three projects in my solution currently: Web, Core, and Data. I would like dependencies to be Web -> Core <- Data, with no dependency between Web and Data at all. This requires my entities to actually exist in Core, rather than Data (where my edmx is). Currently, my thought is to move the Entities.tt file to Core and change the inputFile to point to my edmx in Data to generate my Entities in Core. But I'm unsure what to do with the Context. It's heavily dependent on EF and therefore I don't simply want to move that into Core. I thought about interfacing it, creating my own IEntities.Context.tt and dropping that in Core. My concern is the loss of functionality if my interface doesn't create DbSets and DbContext.
Two thoughts I've been having on this are, 1) put a ref to System.Data.Entity in Core, 2) don't use DbSet and replace it with ICollection (or some such generic container) and wrap DbContext as just an Object in my interface.
Any insight would be very appreciated. Thank you.
There are lots of different patterns you could use, but two come to mind immediately:
1) Add a business / service layer - this will abstract between your data layer and your presentation layer. This is the approach I take most often - using AutoMapper and Dependency Injection (I like Ninject) to make the monkey work easier. Your business layer would expose either its own version of your database objects (not recommended), or objects which related to your business model (a more robust approach).
2) Use the Inversion of Control pattern - Very popular at the moment, though I'm yet to give it a bash in a real life scenario. Apparently very good for TDD / mocking etc... it basically means that your data layer has a dependency on your business layer instead of the other way around.
FYI - My "Core" or "Common" assemblies know nothing about my business or data layers - they merely provide platform agnostic helpers and common classes - if I want to create common MVC functionality, for example, I'll create a Company.MVC.Core assembly instead.
If your solution is completely greenfield then I like to use a code first approach in entity framework (forgive the shameless plug but I've put a tutorial on my blog about this http://www.terric.co.uk/code-first-entity-framework-and-sql-migrations/). I like the control it gives me that I can't seem to get when I generate a .edmx.
Moving onto structure, I usually separate the layers of my project into separate assemblies: Domain (and Data) and WebUI structured with the following folders (namespaces):
Domain (business layer and data layer assembly)
Data (contains my EF data context and Interface to the context)
Entities (contains my POCO objects for the context)
WebUI (presentation layer assembly)
Infrastructure (contains my dependency inject initialiser)
I never DI my entities and instead use the concretes in my presentation layer, however the context I'll always DI as I may want / have to use ADO.Net (especially for legacy apps) where my Domain layer will still use ADO.Net to read / write my POCO entities. This way, when I eventually get scope to implementing an ORM with my legacy app I can simply DI the ORM version of my Domain.
As a footnote to this, if you were following the repository pattern you could always interface them and DI your repositories. Either way, your POCOs should be specific to the solution so the underlying data structure doesn't dramatically change often hence I never DI them.

Whats a recommended solution structure for a somewhat large website in asp.net

Im currently trying to refactor a project(asp.net mvc) that doesnt have any separation at all. just folders :s
The project has a bunch of EF Code First classes (People.cs, Exam.cs,
Message.cs, etc)
The project has several repositories (which all use EF Data
Context)
And of course a lot of controllers and viewmodels
We have a Tests Project but we arent very good at TDD so its not something we are really working on as of now.
I would like to have a clearer separation on the different responsibilities that the project has to address and would appreciate some advice on a good project structure that achieves this.
Please help.
thanks in advance
I would suggest following a Domain Driven Design (DDD) and one suggested way of laying this out would be creating the following projects:
Company.Project.Web <-- Your MVC Application, though you can still use WebForms
Company.Project.Domain <-- Data Transfer Objects (DTO's), ViewModels, Business Logic, Events
Company.Project.Data <-- Repository Interfaces
Company.Project.Data.EF <-- EntityFramework Specific Implementation of Repositories
Company.Project.Model <-- Your EF CodeFirst Classes
Company.Common <-- A common project of utilities and/or extensions
I would suggest you take a look at Project Silk http://silk.codeplex.com/ from the patterns and practices team. Great reference implementation of DDD, Repository, and MVC as well as mixing in HTML 5 and jQuery (vNext).
We use a similar design to that mentioned by jdmonty but a bit simpler. We do the following:
ApplicationName.Web - MVC Application
ApplicationName.Services - Business logic
ApplicationName.Domain - EF CodeFirst classes and the repositories
that act on them
ApplicationName.Common - Classes and utilities used by multiple
projects
ApplicationName.Tests - Test for the various projects
The Web project is dependent upon the Services project. The Services project is dependent upon the Domain project.

Handling Dependency Injections - Where does the logic go?

I'm working on an ASP.Net website along with a supporting Class Library for my Business Logic, Data Access code, etc.
I'm EXTREMELY new and unfamiliar with the Unity Framework and Dependency Injection as a whole. However, I've managed to get it working by following the source code for the ASP.NET 3.5 Portal Starter Kit on codeplex. But herein lies the problem:
The Class Library is setup with Unity and several of my classes have [Dependency] attributes on their properties (I'm exclusively using property setter injections for this). However, the Global.asax is telling Unity how to handle the injections....in the Class Library.
Is this best practice or should the Class Library be handle it's own injections so that I can re-use the library with other websites, webapps or applications? If that is indeed the case, where would the injection code go in this instance?
I'm not sure how clear the question is. Please let me know if I need to explain more.
Though not familiar with Unity (StructureMap user) The final mappings should live in the consuming application. You can have the dll you are using define those mappings, but you also want to be able to override them when needed. Like say you need an instance of IFoo, and you have one mapped in your Class Library, but you've added a new one to use that just lives in the website. Having the mappings defined in the site allows you to keep things loosely coupled, or else why are you using a DI container?
Personally I try and code things to facilitate an IOC container but never will try and force an IOC container into a project.
My solution breakdown goes roughly:
(Each one of these are projects).
Project.Domain
Project.Persistence.Implementation
Project.Services.Implementation
Project.DIInjectionRegistration
Project.ASPNetMVCFrontEnd (I use MVC, but it doesn't matter).
I try to maintain strict boundaries about projects references. The actual frontend project cannot contain any *.Implementation projects directly. (The *.implementation projects contain the actual implementations of the interfaces in domain in this case). So the ASPNetMVCFrontEnd has references to the Domain and the DIInjectionWhatever and to my DI container.
In the Project.DIInjectionWhatever I tie all the pieces together. So this project has all the references to the implementations and to the DI framework. It contains the code that does the registering of components. Autofac lets me breakdown component registration easily, so that's why I took this approach.
In the example here I don't have any references to the container in my implementation projects. There's nothing wrong with it, and if your implementation requires it, then go ahead.

Where should I place additional classes in my MVC application

I have an ASP.NET MVC application which is using Linq to SQL classes placed in the Model folder.
I want to create some extra classes that I would normally place in my BLL but I'm not sure how to work this with MVC.
With WebForms I would have my DAL as a Class Library.
My BLL as a class library that referenced my BLL.
My Web Site that referenced both the DAL and BLL.
The problem I am facing is, if I create a class library, this will need to reference my MVC Application because it will need to use the types contained in my Model.
If I then add (or try to add) a reference to my class library, I will get a circular dependency.
In Web Forms. My other option would be to place the classes in the App_Code.
Is there an equivalent of App_Code in a MVC application?
You can move all your models to the class library, can't you? Neither MVC or VS mind. This would remove the dependency of the Models library on the Web app.
You can place that in the model folder. As all the business related classed are place into that folder
For better practice see the scottgu the nerddinner examples. He has created the respiratory classes in nerdinner application.
I agree in terms of the Model folder. You can organize it to your heart's content (BLL, DAL, etc.).
I personally would avoid doing a separate assembly unless you have a compelling reason to. Being the kind of developer that tends to over-complicate problems if I'm not careful, I try to follow the KISS (Keep It Simple Stupid) practices as much as possible, which tends to keep me out of a certain amount of trouble.
Try taking a look at S#arp Architecture. You can either use the template they provide or use it as a reference to help you make decisions.
http://code.google.com/p/sharp-architecture/

Resources