why a ioc framework for MVC 3? - asp.net-mvc-3

After plenty of reading, I still don't understand Unity for MVC 3.
Specific points
Why use it? I can create a controller that in its constructor, it takes a new EF context for testing.
How? I keep seeing bits are parts, but is there an end to end walk through on implementing Unity on MVC 3 (Live)? There seem to be plenty on Beta and RC, but the code always seems to have a problem on live frameworks.
Currently this is not impacting my unit testing, since my controllers have overloaded constructors, as does my EF context.

If you have a small project, you may not benefit from IoC.
Lifetime management if a plus for me. I don't have to dispose a repository (or service layer) in every controller. It thins out my code and creates the object for me. In addition, I know I have a clean separation in case I ever need to change things. It almost forces me to. I use for example IRepository that is backed by entity framework. For testing I use a fake IRepository implementation. So sure, I could manually create it in my application but this leads to some bad practices in larger projects and I lose the benefits of having the interface.
I have a basic demo for a super short talk I did recently on this for (15 minutes) mvc and unity for dependency injection using the unity.mvc3 nuget package:
http://completedevelopment.blogspot.com/2011/12/using-dependency-injection-with-mvc.html
Btw. Dependency Injection in .Net - best book on the subject without a doubt.

It's very useful for wiring up all your dependencies, handling life cycle of your objects, error handling, transaction handling, testing purposes and ...
All of above point are advantages of using an IoC framework, but I strongly recommend using Ninject. it has a very friendly DSL for binding modules, has out of box library and extensions for ASP.NET MVC and is an open source lightweight DI framework.
It has also many extensions.

Related

Using Laravel contracts in Application/Domain layers

I'm building application at top of the Laravel. In my Domain layer I have services. One of these needs to send an EMail. Laravel has Illuminate\Mail package for these purposes.
But Mailer contract depends on \Illuminate\Mail\PendingMail class.
https://github.com/laravel/framework/blob/5.7/src/Illuminate/Contracts/Mail/Mailer.php
Does it mean I need to write my own interface (port) for my Domain layer to fully decouple my application from framework?
To be honest, I'm not sure what you are asking. But I'll try to answer anway.
If you use (any) framework functionality directly in your code, you obviously couple your application to the framework. That's the whole point of a framework. It offers you a lot of functionalities that are commonly used throughout different types of applications. It can be seen as foundation for an applciation. These functionalities are often made available through interfaces, so that the implementation can be swapped out if necessary. Swapping out the implementation doesn't make your application less coupled to the framework though. It just allows you to use a different kind of implementation; the interface will still be a framework one.
So, the only way to prevent (heavy) coupling with a framework would be to write your own interfaces that abstract all the framework functionalities. You could then have proxy classes that implement these new interfaces and do nothing else than proxying requests to the proper functions of the framework, allowing you to write other proxy classes in future for a different framework.
If you ask me, this sounds like a bad idea though. Because in the end, you are building your own framework based on your own interfaces. So you are using additional custom code which adds no additional functionality, but comes with the added risk of bugs and errors.

Is the MVC framework sometimes used as only the user interface layer when using dependency injection?

I'm trying to learn dependency injection. The book/example I am following seems to be using an MVC project as just the UI layer within a broader architecture. The example includes a separate project for the domain layer and yet another project for the data access layer.
When I first learned MVC I came away thinking MVC was the entire architecture. V for view for UI layer, C for controller for domain layer, and M for model for data access layer.
So is using an MVC project as only the UI layer a proper and/or commonly accepted application of the MVC framework?
So is using an MVC project as only the UI layer a proper and/or commonly accepted application of the MVC framework?
Yes.
While it is possible to make an application entirely within the context of ASP.NET MVC, doing so means that the application will have to be written from scratch to use a different UI framework. Isolating the business logic into a separate set of services that are not coupled to ASP.NET MVC means that only the top layer would need to be replaced to move to a different UI framework, which also means that the application's lifecycle may extend beyond the end of ASP.NET MVC and/or it can be made into an application with a different UI framework (WebApi, WPF, etc) without too much trouble.
The purpose of dependency injection is to decouple your services from all other parts of the application, including each other. So by extension, it is only natural to build the business layer separately from the UI layer. Whether you physically have them in one assembly or multiple is really just a matter of preference.
Applying SRP to the MVC design pattern will lead you there. Same goes for MVVM. You are extracting logic from Model to other classes like Interactors, Services, Repositories etc.
From any point of view this is perfectly normal(and desirable). Your Model is just an abstraction of Several different layers.
I would suggest you to take a look at VIPER (not a car) - https://www.objc.io/issues/13-architecture/viper/ and you will see something that is occuring to you right now.

How to preserve the MVC methodology using Appcelerator's Modules

I'm using alloy on titanium, I want to use modules but I'm worried about breaking the MVC principles.
How can I achieve this?
Thanks.
In our projects we are using Titanium modules as service layer. (If a piece of business logic will be used in more than one controller, we refactor the logic into a module, so logic can be injected in all controllers). I do not see any violations of the original MVC architecture.
What we're trying to achieve in our projects is close to MVCS architecture (more info here)

Separation of Concerns with Generics for IoC

My project is organized as follows
ASP.NET MVC 3 WebApp
Domain.Core - Interfaces [library]
Domain.Core.Entity - Entities [library]
Infrastructure.Core - Implementation of Interfaces [library]
Infrastructure.IoC - Uses Unity as a means of achieving Inversion of Control [library]
The predicament is as follows:
If I were to add a generic method to an interface in my Domain.Core, such as the following, I get a compile error that asks me to add a reference to Domain.Core.Entity in the Infrastructure.IoC project.
T Get<T>(int Id) where T : EntityBase, new();
T can be a class EntityBase or Blog which inherits from EntityBase or a few other entities that all inherit from EntityBase. The idea is to return an entity based on what child class is provided so that the child class is loaded with the default data that is required for all classes that implement EntityBase.
So, the question is two fold:
Is it better to not reference the Domain.Core.Entity project in the IoC project and keep things clean?
How would I achieve something like the above without having to muddy the cleanliness of references?
Thank you.
Note: I went through a few of the questions here to search for this topic but didn't see any. If you do see it, then let me know and I will delete this question.
With Dependency Injection, it's best to have a single component with the responsibility of composing all the various collaborators. This is the third party in Nat Pryce's concept of Third-Party Connect, or what I call the Composition Root. In the architecture outlined above, this responsibility seems to fall on Infrastructure.IoC, so given this structure, there's nothing wrong with adding a reference from Infrastructure.IoC to Domain.Core.Entity - in fact, I would find it more surprising if it were not so.
However, as an overall bit of feedback, I think it's worth considering what benefit is actually being derived from having a separate Infrastructure.IoC library. The entry point of that application (the ASP.NET MVC application) will need to have a reference to Infrastructure.IoC, which again must have a reference to all libraries in order to compose them. Thus, the ASP.NET MVC application ends up having an indirect reference to all other libraries, and you might as well merge those two.
(Technically, you can decouple the various libraries by relying on some sort of late binding mechanism such as XML configuration or Convention over Configuration, but the conceptual responsibility of Infrastructure.IoC is going to remain the same.)
For more information, you may want to read this answer: Ioc/DI - Why do I have to reference all layers/assemblies in entry application?
Why split the Domain.Core from Domain.Core.Entity? And why split Infrastructure.Core from Infrastructure.IoC?
I think you can get away with a 3 project structure:
Domain - has no dependencies on the other 2 projects. May contain entities and interfaces.
Infrastructure - contains interface implementations and the Unity container. Depends only on Domain project.
MVC - depends on both Domain and Infrastructure.
If you are worried about programming against concrete classes instead of interfaces, give the classes in the Infrastructure project a different namespace. You should then only have to use that namespace maybe a couple of times (in Global.asax or bootstrapper) if at all.
This way it is very clear what projects depend on what. Since you are using unity, this is a form of onion architecture. If you find later that you should split Infrastructure or Domain out into more than 1 project, you can refactor.
IMO, dependencies only get muddy or unclean when you have references like System.Web.Mvc or Microsoft.Practices.Unity in your domain project(s). Like Mark says in his answer, the outer layers of your "onion" will have dependencies on the inner layers, there's not much you can do to avoid that. But try to make the domain concentrate on its core business, avoiding as much detail of how it will be used in a UI as possible.

Example use-cases for using Dependency Injection with the Play Framework

I am a big fan of Dependency Injection and the Play Framework, but am having trouble seeing how the two could be exploited together.
There are modules for Spring and Guice, but the way that Play works makes it hard for me to see how DI could be beneficial beyond some quite simple cases.
A good example of this is that Play expects JPA work to be done by static methods associated with the entity in question:
#Entity
Person extends Model {
public static void delete(long id) {
em().find(id).remove();
}
//etc
}
So there is no need for a PersonManager to be injected into controllers in the way it might for a Spring J2EE application. Instead a controller just calls Person.delete(x).
Obviously, DI is beneficial when there are interfaces with external systems, as the concrete implementation can be mocked for testing etc., but I don't see much benefit for a self-contained Play application.
Does anyone have any good examples? Does anyone use it to inject a Manager-style class into Controllers so that a number of operations can be done within the same transaction, for example?
I believe from this sentence you wrote:
"Does anyone have any good examples? Does anyone use it to inject a Manager-style class into Controllers so that a number of operations can be done within the same transaction, for example?"
that before answering the DI question I should note something: transactions are managed automatically by Play. If you check the model documentation you will see that a transaction is automatically created at the beginning of a request, and committed at the end. You can roll it back via JPA or it will be rolled back if an exception is raised.
I mention this because from the wording of your sentence I'm not sure if you are aware of this.
Now, on DI itself, in my (not-so-extensive) experience with DI, I've seen it used mainly to:
Load the ORM (Hibernate) factory/manager
Load Service classes/DAOs into another class to work with them
Sure, there are more scenarios, but these probably cover most of the real usage. Now:
The first one is irrelevant to Play as you get access to your JPA object and transaction automatically
The second one is quite irrelevant too as you mainly work with static methods in controllers. You may have some helper classes that need to be instantiated, and some may even belong to a hierarchy (common interface) so DI would be beneficial. But you could just as well create your won factory class and get rid of the jars of DI.
There is another matter to consider here: I'm not so sure about Guice, but Spring is not only DI, it also provides a lot of extra functionalities which depend on the DI module. So maybe you don't want to use DI in Play, but you want to take advantage of the Spring tools and they will use DI, albeit indirectly (via xml configuration).
The problem in my humble opinion on the static initialization approach of Play! is that it makes testing harder. Once you approach the HTTP vs Object Orientation problem with static members and objects that carries the HTTP message data (request and response) you make a trade of having to create new instances for each request by the ability of make your objects loosely coupled with the rest of your project classes.
One good example of a different design are servlets, it also extends a base class but it approaches the problem with a single instance creation (by default, because there are configurations that enable more instances).
I believe that maybe a mix of the two approaches would be better, having a singleton of each controller would give the same characteristics of a full static class and would allow dependency injection of some kinds of object. But not the objects with request or session scope, once the controller would need to be created every new request. Moreover it would improve testability by inverting the control of dependency injection, thus allowing arbitrary injection points.
Dependencies would be injected by the container or by a test, probably using mocks for the heavy stuff that much likely would already have been tested before.
In my point of view, this static model pushes the developer away from testing controllers because extending FunctionalTest starts the application server, thus paying the price of heavy objects like repositories, services, crawlers, http clients, etc. I don't want to wait a lot of objects to be bootstrapped just to check if some code was executed on the controller, tests should be quick and clear to make developers love them as their programming assistant/guide.
DI is not the ultimate solution to use everywhere... Don't use DI just because you have it in your hands... In play, you don't need DI to develop controllers/models etc... but sometimes it could be a nice design: IMO, you could use it if you have a service with a well know interface but you would like to develop this service outside Play and test it outside play and even test your play project with just a dummy service in order NOT to depend on the full service implementation. Therefore DI can be interesting: you plug the service loosely in play. In fact, this is the original use case for DI afaik...
I just wrote a blog post about setting up a Play Framework application with Google Guice. http://geeks.aretotally.in/dependency-injection-with-play-framework-and-google-guice
I see some benefits, especially when a component of your application requires a different behavior based on a certain context or something like that. But I def believe people should be selective about what goes into a DI context.
It shows again that you should only use dependencies injection if you really have a benefit. If you have complex services it's useful, but in many cases it's not. Read the chapter about models in the play-documentation.
So to give you an example where you can use DI with play. Perhaps you must make a complex calculation, or you create a pdf with a report-engine. There I think DI can be useful, specially for testing. There I think the guice-module and spring-module are useful and can help you.
Niels
As of a year and some change later, Play 2.1 now has support for dependency injection in controllers. Here's their demo project using Spring 3, which lays it out pretty clearly.
Edit: here's another example using Guice and Scala, if that's your poison.

Resources