Assume a web project by ASP.NET MVC 5 and OWIN/Identity membership. The IoC is done with Unity. Everything is within one project now.
Question: Does it make any sense to separate MVC, Idenity and IoC to isolated projects and encapsulate Identity into some IAccountService to be resolved by Unity in MVC project?
The question seems to be quite silly, but my rubber duck keeps silence for unknown reasons, any guess?
The goal I want to achieve looks like this
ASP.NET MVC (OWIN) --> IoC (Unity) --> AccountServiceImpl --> Identity
Both MVC, IoC --> Contracts (IAccountService)
where --> is a project reference
I need it to be able to change IoC container and also I need Identity data to be accessed from another projects through an interface
Yes, it is safe to separate your solution into smaller projects such as MVC, Identity and IoC.
At least, that's my short answer.
Does it make sense? The long answer is a little bit more complicated. I've answered some similar questions before where I address solution and project architecture:
where should the interfaces be defined?
Where should I put automapper code?
In the answer above, I explained
[...] I have a typical structure like this:
MyProject.Core
MyProject.Domain
MyProject.DependencyInjection
MyProject.Infrastructure
MyProject.Web
MyProject.Tests
Jeffrey Palermo encourages the use of Onion Architecture. In part 4 of his article on Onion Architecture, Jeffrey provides an example solution with the following structure
Core
Infrastructure
IntegrationTests
UI
UnitTests
However, Jimmy Bogard somewhat disagrees with me and my approach.
In Evolutionary Project Structure, Jimmy explains:
I used to care quite a bit about project structure in applications. Trying to enforce logical layering through physical projects, I would start off a project by defaulting to building an app with at least two projects, if not more.
Indeed, Jimmy describes his previously-preferred solution architecture style as being similar to the style that I've mentioned above.
Jimmy goes further to say that "deciding about project structure is a waste of time and energy". He actually prefers a simpler solution structure. That is, very little.
Although Jimmy does clarify his position by saying:
I have absolutely nothing against layered software design. Using project structure to do so is a waste of time if you only have 1 app you're deploying [...]
(Emphasis mine)
If you have other applications needing to reference aspects of your MVC solution, it may very well make sense to split them out into their own projects so that you can easily reference them.
I think what we should conclude is that:
Solution architecture isn't a rule or a law. Separate projects out where it makes sense.
Make sure your solution is easy to maintain and easily understood by others. Don't over-complicate your solution.
I'll add my 0.02¢ to the excellent answer from Rowan. I'll say more about actual Identity implementation.
As far as ASP.Net Identity framework goes - it might be slightly tricky to move it out of MVC project into higher (or lower, depends how you place it) sitting layer. I'm pretty sure you'd want to have ApplicationUser object in your domain layer. But ApplicationUser depends on IdentityUser which depends on Identity.EntityFramework, depending on EntityFramework. And adding EF to your domain project might go slightly against the rules of Onion Architecture.
Also ApplicationUserManager from Identity framework is massive (in terms of number of methods) and also depends on EF. So hiding it behind an interface can be tricky.
So really you have 2 options:
Take a hit and add EF into your domain project and have ApplicationUser and ApplicationUserManager classes in your Domain layer. And don't wrap UserManager in an interface for multiple reasons.
Take a hit in different way and leave all Identity stuff in your MVC layer, identify very small set of actions that you need to execute from Domain layer and add a tiny interface on top of ApplicationUserManager.
I have tried both and both approaches in different projects and both work equally well. I have tried adding interface on top of ApplicationUserManager and failed - mostly because of the size of the class, also it is aimed to work in async manner and there are sync-wrappers. Sync wrappers will not work with your interface - because strong-typing.
I've written a blog-post about applying DI to Identity framework and there is a discussion in the comments about layers separating - have a look for ideas.
Related
Ironically, the problem DI is trying to solve, is exactly the problem that has been created in the project. Are there any resources for using the framework where i'm capable of picking and choosing which features I want to use/enable and those i want to omit?
It's very hard to manage dependencies and develop a modular and well-structured application without using dependency injection techniques.
Which i strongly disagree with; and believe to be the opposite, as there are plenty of cases where it's common without DI than with it.
Currently, i'm stuck on trying to use the project by calling all of the classes manually, as the DI is broken and constantly prone to errors, with vague or unhelpful exceptions being thrown and preventing app from executing. I'm unable to properly and thoroughly debug it, and that isnt the kind of assistance i'm seeking.
Strictly the question being posed is, i want to use the framework without using dependency injection, are there solutions; if yes, can you provide them in the form of step-by-step, or copy-paste? Can i use the framework without it, or am i tasked with writing my own because it's unable to keep it's functions modular?
My solution so far, is i'm attempting to restructure, the entire framework to remove the DI logic from the foundation of the framework (it's coupled inside [root] functions instead of beside them?); but i'm not sure if there are ways around it, and if possible to just strictly not use it if i dont want it enabled.
I've already created a repository class that's based on interface, then i've made some changes to a few manager classes that use the repository... but then there's stores, other managers (repetitive layers stacked inside each other), cache (not sure why it's layered into foundation), UoW (dont need this, cant null it out), publishers (dont know how to pull this one out), and a whole bunch of other, logic inside logic, that dont need to be structured the way the project is layered. The whole thing feels more like a Jenga tower, than a flexible framework where isolation of responsibilities is at core of development practice.
EDIT
Related StackOverFlow Problems:
AspNet Core3 Identity configuration
What i've attempted:
Multiple Identities in ASP.NET Core 2.0
ASP.NET Identity without Entity Framework
How to resolve generic interface to generic implementation when using dependency injection?
How to implement Unit Of Work pattern with Dapper? (used this to make Abp.UoW interface nullable, but there's still other areas of forced UoW logic in-between functions in core layers of framework)
Basically, any search results containing "without dbcontext", "without entityframework", "without dependency injection", "using dapper", that all contained "asp identity" were search queries i was using.
Before modification and after modifications (attempts at using my own app services and domain model) all yielded
An error occurred while starting the application.
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.AspNetCore.Identity...
which is basically dependency injection breaking, and not being clear as to what the issue is, besides... "you cant use this class that inherits interface/abstract class that's referenced throughout framework and by DI." So i prefer not to use DI, and work around it, since solutions arent reliable to resolving my issues.
I hope I don't sound to pedantic, but your "without DI example" is still an example of DI. You apply constructor injection, which is a form of DI. What I understand is that you want to apply Pure DI instead of using the built-in DI Container. There are advantages of using Pure DI of using a DI Container, which is, for instance, described in:
When to use a DI Container by Mark Seemann,
When should you use a container? by me,
and about three quarters of our book on DI focuses on applying DI by hand, i.e. Pure DI.
Now for the bad news...
When working with ASP.NET Core (and most of the framework that depends on the .NET Core DI Container), you can never completely replace that DI Container with a Pure DI option. That shouldn't be a problem, however. Just think of ASP.NET Core's Container as its configuration system. Consider the simplistic configuration system of ASP.NET (classic) MVC; its configuration system consisted just of a large dictionary. Although you were able to replace services in the dictionary, you couldn't remove the dictionary all together. It was just too embedded with the system. The same holds with ASP.NET Core's configuration system. The whole framework completely depends on its existence. And chances are slim that Boilerplate allows you to work without it.
But there's some good news...
Even though you can't remove the built-in configuration system, you can choose to apply Pure DI to your own application components and if you wish, you could even go back to the old school tightly coupled code base if you really want (which I can see from your examples you don't, fortunately).
How to do this with ASP.NET Boilerplate exactly I can't tell, unfortunately. But the freely available code samples of my book do demonstrate this concept using ASP.NET Core MVC here and especially here.
I am new to iOS development, so please excuse me in case my question sounds trivial.
I am planning to introduce MVP or VIPER pattern. I am from Web background and in web application we used to follow different layers/dlls (for model, view, common etc.). Does it make sense to follow the same layered approach (frameworks in this case) in iOS and or it will be overkill? I have not come across any sample project (based on MVP) which create different framework for model, View and Presenters? It would be great if someone can share any sample project (based on MVP) which we can use as a starter project.
Thanks In Advance
In iOS, we generally use MVC - Model/View/Controller. So, if you're looking for the analog in the iOS world, that's it. If you're saying that you've really dug into MVC and there's something that you find deeply unsatisfying, and therefore want to introduce a different pattern, then that's a different question.
So, no, the sort of logical separation of responsibilities that you see in approaches like MVC is not overkill. In fact, the division of "view" and "controller" classes are fairly central to everything we do (e.g. UIView subclasses, UIViewController subclasses, etc.), so the only thing you really have to do is design appropriate "model" classes and you're off to the races.
But, in answer to your question, you don't generally use separate framework targets for the model, the views, and the controllers. That probably would be overkill. Usually you can keep track of everything through through judicious use of Xcode groups/folders within your project. We generally only pull stuff into frameworks for more technical or logistical reasons (live views, app extensions, sharing code between multiple apps, etc. ... see WWDC 2015 Building Modern Frameworks for discussions of when you'd generally use frameworks).
But to the question of MVC vs MVP or VIPER (or MVVM or whatever). I'd suggest that you simply embrace the shared spirit of all of these patterns (namely the separation of responsibilities) and apply it to your iOS MVC code. Once you've got some iOS experience under your belt, you can then re-evaluate this pattern question.
If you're starting with iOS developement and is looking for a good architecture, go with VIPER. It's not at all an overkill as long as you:
1 - Automate VIPER files generation
2 - Automate VIPER modules initialization
To accomplish both requirements above, use this Xcode plugin (https://github.com/natangr/ViperTemplate) to generate and intialize VIPER files automatically. It works like charm!
And read this post https://www.ckl.io/blog/best-practices-viper-architecture to get more tips on how to automate things when using VIPER.
I do use it, even for very small projects (160h of development)
I am in the process of determining a fairly simple layered architecture for a .NET MVC application that has a repository layer and a service layer. I have found some fairly clear and simple examples, notably www.asp.net, and some questions and answers here, but I am looking for something that is a little simpler, suitable for small applications, but that uses different projects, to get the idea across. The example I linked to above has the repository and service as classes in the Models namespace. That just isn't enough of a clear separation for me to be able to illustrate it properly.
I have a separate project for the repository that implements interface IRepository. There is a separarate project for the Service that implements IService and takes an IRepository (constructor injection). The Service implements IService. It is enough for this example that the controller instantiate the service, no need for an IoC container just yet. Think of it as an intermediate step to understanding best architectural practices, part of a sequence that builds progressively to include dependency injection and possibly more layers.
The question is, where should I define IRepository and IService? Both the service and repository projects need to reference them, of course. It seems clear then that they should be defined in another project referenced by both the service and repository projects. If so, what would a good naming convention be? Something like XXXXContracts?
Likewise, for the data models passed between the presentation, service and repository layers, is it acceptable to have a separate project called XXXXModels referenced by all the layers? I understand that in some cases the models passed between the service and repository layer can differ from those passed between the service layer and the presentation layer, but the principle is the same.
I have found answers to similar questions here, but they tend to involve a more complicated architecture than what I have outlined here. I'm looking to achieve a really simple and clean illustration of the two layers that can be seen as a step or two above referencing the data layer and having business logic in the controllers, that's all. I know there is a strong and valid argument for going straight to the full-blown best practice, but not everyone is suited to making that jump in one go.
Introduction
This is something I've asked myself as well. One burning question I always have is similar to yours;
what would a good naming convention be?
How should I name things? Should they go in folders or projects?
After searching around I suspect the answer is that it doesn't really matter. What's important is that you solution has some sensible architecture and that you try to follow good practices such as SOLID.
My ASP.NET MVC heroes on this topic are Jeffrey Palermo, Steve Smith and Jimmy Bogard.
Onion Architecture
Jeffrey Palermo discusses a combination of old ideas but brings them together and gives it the visually stimulating name of Onion Architecture (a recommended read). Jeffrey shows a good approach to the problem of where to put things. He explains that at the centre (or top) of your application you have your Core. This layer is where you should put interfaces such as IRepository and IService.
Almost all of your interfaces should go in the core and everything else (other projects) can all reference the core. This way everything knows the skeletal structure of the application without knowing the implementation details.
Try to have your UI layer reference as little as possible (within reason). In one of my applications my UI (MVC) layer only references the Core. Everything it needs is injected into it with Dependency Injection.
Steve Smith discusses Onion Architecture and similar ideas with demonstrations in MVC Solution Best Practices: A solution to the solution problem
My solution
In my MVC solutions I have a typical structure like this:
MyProject.Core
MyProject.Domain
MyProject.DependencyInjection
MyProject.Infrastructure
MyProject.Web
MyProject.Tests
The Core contains my interfaces. It is usually divided up into folders like Services, Models, Domain, Repositories and so on.
The Domain layer references only the core and contains my implementation. It provides a lot of the concrete classes for the domain abstraction in the core. It deals with a lot of business logic, processing, command handling, manager classes, concrete service implementations and so on. I consider it a fairly inner-layer and so it references as little as possible.
The DependencyInjection layer contains my chosen DI package/framework and implementation details. I consider it an outer layer; similar to UI or Infrastructure and so it's ok if it references a lot. It's not necessary for this layer to be a separate project and many people will tell you not to do this. That's ok; do what works for the complexity of your project. I like my DI to be its own thing. The good thing about it being so separate is that I could replace the DI framework with a different one and things would be fine. No layers reference the DI project.
The Infrastructure layer contains information about logging, emailing and data access. It will contain my ORM of choice. It's not business-logic stuff and it's not UI stuff. It's the railroad of my solution to get things done. It's on the outer layer but it only references the Core.
The Web layer is my MVC project and only references the Core.
Complexity and final thoughts
I have found answers to similar questions here, but they tend to involve a more complicated architecture than what I have outlined here
It's a good point. It's important to keep in mind the complexity of your problem. But don't be deterred by good solution practices. My solution and Onion Architecture are not necessarily very complex and don't really bloat your solution. They just keep things separate.
In Evolutionary Project Structure, Jimmy Bogard talks about things being over-complex. If what I've said seems too complex, follow Jimmy's advice and put it all in the one project (your UI layer). That's ok - as long as it suits you.
Remember to take my solution only as an idea - something to consider; my approach is an attempt to follow sage advice from the best, but I'm sure I've only succeeded so much; I can (and must) still improve.
Background
I am coming from 3 tier architecture of ASP.NET background. I have used Unit Tests directly on layers and never tried mocking of layers. All application are developed with EF Database First and separate POCOs and Infrastructure project handles the plumbing work of the application. Applications developed are of small to medium size.
Progress so far
Since I started learning ASP.NET MVC, One of the first questions was to how to create layers for solution. For last 15 days I am learning and hunting for good architecture to learn and follow in this and future MVC projects. I have went through following architecture patterns/sites and found them too complex for my own good. Some of the main concerns
Inherit complexity of the project which makes it difficult to work with for new programmers
Sharp learning curve
Too many unit tests for every layer to test redundant behaviors (minor)
Relatively slow compilation during development
Sites / Project I tried
Sharp Architecture
Onion Architecture
Neard Dinner
Project SiLK (Microsoft)
Main Dilemmas
I found that most common thing among these projects is Repository Patterns and Dependency Injection (IoC). Though I do not have anything against it, I found it hard to maintain and understand projects. I have executed fairly large projects with 3 tier architecture, with so-called "tight coupling" with adequate Unit tests to test the project. I feel architecture will be better off without these involved.
Huge emphasis on TDD and DDD
Concept of loosely coupled is far stretched
Loosing focus on MVC as pattern and dominating architecture with other parts
Required Simple, easy to understand, maintainable architecture for MVC projects
Note: I came across this good implementation structure from jimmy bogard’s Organizing ASP.NET MVC solutions. I would still appreciate any suggestions on this topic.
Background
After so much of looking backward and forward I have settled on using Onion Architecture for my ASP.NET MVC WebAPI project.
In this course I found my self struggling to keep up with new development methodologies and frameworks. Fact is whoever is looking for creating new application based on three tier structure or similar existing structure, need to "let go" and embrace new foundations. Advances in the new development philosophies like TDD and BDD are immense and are nothing but helpful.
Web and supported technologies are different beasts than that I know of. Truth is MVC and MVC WebAPI got developed cause existing Web Forms framework could not keep up with new developments.
Technology Stack
It took time and patience to unlearn and learn. But finally I find myself at new level and with the flow of mainstream developments. Following is final technology stack adopted by me (in no particular order).
Backend
ASP.net MVC WebPI
Onion Architecture
EF database first (cause it was suited for my project)
Generic Repositories
Frontend
Bootstrap UI (as UI design framework and skipped jQuery UI)
Typescript (for strongly typed JavaScript, so no direct JS in project)
AngularJS (as front-end MVC)
LESS CSS (for robust and maintainable CSS, so no direct CSS in project)
Breeze.js (for model binding and change tracking)
Testing
- In process of finalizing
Along with above I have used and created bunch of T4 templates to take care of redundant tasks. I would suggest master yourself in it. It reduces development time considerably. I am still making my mind for some of the tools and project and testing. I will post the finalized stack of it once am done.
Above stack may look comprehensive but I found myself it as necessity to built highly maintainable and responsive web application. As I mentioned before, it takes time, but once you are familiar with it, it makes sense.
Note: Of all, learning curve of AngularJS very steep and you will find yourself going back and forth on decision to use it. But stick to it, its worth it.
#Steven: Thanks a bunch for your link, it really was corner stone for me to unravel mysteries of new Web.
Required Simple, easy to understand, maintainable architecture for MVC
projects
Go for NidoFramework. It is just what you are looking for. It is free, simple, well design code framework with a good architectural pattern.
I must say Nido framework will hit the head of the nail for you for your requirement..
Link: https://nidoframework.codeplex.com
Download from NuGet
I am going to use it in a project with less-experienced developers so a complex framework such as Spring.NET is not an option. I was thinking about:
Ninject
Castle Windsor
StructureMap
Which would present a moderate learning curve without losing flexibility?
and another question - where is the correct place to put the configuration? Since the kernel/configuration on a 3-tier ASP.NET application (not MVC!!! all examples are using MVC :) )
The great thing about proper use of DI is that you can defer the decision about which DI Container to use until the last responsible moment. In application architecture terms, this corresponds to a so-called Composition Root, which is where you wire all depedendencies together. This is often the application's entry point.
Apart from the Composition Root, the entire application can be written without referencing any particular DI Container at all. You just need to follow well-known patterns and principles.
When it comes to pick a DI Container, I'm aware of these DI Containers for .NET:
Castle Windsor
StructureMap
Unity
Autofac
Ninject
Spring.NET
Personally, I have been happy with Castle Windsor so far, but I have yet to gain extensive experience with all of these containers.
Here's an ASP.NET (not MVC) Ninject sample:
http://davidhayden.com/blog/dave/archive/2008/06/20/NinjectDependencyInjectionASPNETWebPagesSample.aspx
I have used ninject and found it easy to bring new developers up to speed with it.
Consider to start with wiring by hand: see http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion . It gives less-experienced developers a better insight in the basics of IOC/DI.
I think you are being too hasty to reject spring.net. Spring offers an extremely flexible learning curve, so at the beginning it's kind of "you take what you want from it" approach.
You can start with the simplest-of-all IoC container, and later on move to aop, transactions, unit testing, or whatever you desire, so the complexity builds up gradually.
This was the #1 selling point at my last two jobs for using Spring. Additional points were:
It doesn't force you to use its api or to bend your architecture. Again, this leads you to adapt its features at your own pace.
Very extensive documentation.
When the project matures, so will your developers, so spring will come out handy at the end ... (at no cost in the beginning, in my opinion)
Autofac is my container of choice. It allows registration via lambda expressions for maximum flexibility (the link has some nice examples).
It also has a Silverlight-compatible version. I'm unsure if the other containers do.
As for placement, the container should be built during application startup. For an ASP.NET application, this would be in the Global.Application_Start method.
Autofac has ASP.NET integration which injects pages instances using the container you build during startup.
Have a look at http://funq.codeplex.com/ first of all it's extremely fast compared to windsor and other reflection based containers second of all it's very flexible but still has a very readable configuration (If you've gotten your head around Lamba expressions which should take to long any ways)
We use the managed extensibility framework. It is part of the .NET 4.0 framework (currently in release candidate), where you can find it in the System.ComponentModel.Composition namespace. The codeplex site is currently still the best source of documentation.
The focus of MEF is more on "extensibility" rather than "dependency injection", but it uses dependency injection to achieve this. For example, the visual studio 2010 code editor uses MEF to enable extensibility.
We use it as a DI framework and have not yet run into any problems (though I did need the dynamic instantiation sample which is not part of the core yet).
If you're yet familiar with any DI framework, I'd go with the Simple Injector.
It has a very simple API, that will get you started very quickly. Although simple, it still enables many advanced configuration scenario's. The library designed with migration in mind, which means that switching to another framework would is rather straightforward. To prove this point, there is an migration guide on the project's wiki.
In addition to Ninject, which is a great product, there are also two other options that I'm familiar with:
Microsoft's Unity. Some Alt.NET folks think it's a little on the big & complicated side. I've been using it for several months now as part of Prism (Prism is NOT required to use Unity. It's available stand-alone) and I've found it to be simple and straight-forward.
StructureMap. I've found StructureMap to also have a very gentle learning curve with fast ramp up.
Hope this helps.
I find StructureMap very usefull and intuitive to use. I played with Ninject a bit and found that less convenient, but YMMV. I would also recommend you use the common service locator as an intermediary between the actual implementation of your IOC and your application. When you want to switch your IOC/DI container later on, this is less painfull. There are adapters for StructureMap and Castle windsor. And I think from googling that there also is an adapter for Ninject 2 according to this blog.