Why method of controllers in Play! framework are static - dependency-injection

I am using Play! framework 1.2.5 for one of my application. Initially I was resolving dependencies either by creating new instance of the class or using factory. But my application grows and it becomes harder to manage dependencies in such way. I'm going to move to dependency injection with Google Guice
Looks like, for every controller, I have to write
requestStaticInjection(MyController.class);
to inject service in controller
#Inject
static MyService mySerivce;
This is frustrating, I don't like that controllers has static methods and can access only static variables. I would like to pass dependencies to constructor of controller and I don't want to declare static fields.
Why methods of play controllers are static ? Is it some kind of limitation ? Is there are other good way to inject classes into Play! controllers

Old question, but I got the same problem and I found my answer here http://typesafe.com/blog/announcing-play-framework-21-the-high-velocit Though, It's not for the same Play version as you are using...
Play 2.1 now supports a new routes syntax that enables calling injected controllers instead of static methods. Simply prefix the controller method in the routes files with an "#" symbol
GET / #controllers.Application.index()
in your conf/routes

Is there are other good way to inject classes into Play! controllers
No. You should not create a service in a controller - make it a regular class that does not extend Controller. Then call the service class from your controller. Keep your controller code to a minimum - there is a lot of bytecode magic there, so keep controller code simple (lookup object, render results, that sort of thing)

Related

Force .NET MVC Controller to Call Service Methods Rather Than Directly Calling Base Class

I have a standard class stack in a .NET MVC5 using Entity Framework 6:
MyController()
MyService() : ServiceBase()
ServiceBase() : IServiceBase
All methods/classes are public at the moment.
ServiceBase() contains generic(T) methods and is inherited by all services.
The problem is that MyController() can call the generic methods in ServiceBase() directly. Important properties need to be set on the Entity before being passed to ServiceBase().
Is there any way to hide the ServiceBase() methods from MyController() forcing MyController() to go through MyService() rather than calling ServiceBase() methods directly?
Thanks all.
Why are you starting from an interface? I think you are getting your OO a little confused. I think the problem you are having is that you start at an interface, which doesn't have method visiblity controls. So you try to hide it in ServiceBase, but MyService has to know about the interface so that is why you cannot change visibility midway through.
I would suggest you rethink your OO strategy a bit.
However, if you really want to keep the interface and hide the methods in the base class, you can blank them out in MyService and inside of another method of MyService you can directly call the base class. I have created an example here.
But like I said, I would discourage this behavior and come up with a better OO strategy. If you can get around to posting your code, perhaps in a separate question, then I and the rest of the community can help you out with that. FYI, this might go better in the codereview stackexchange site.
The answer is to make the base classes that I don't want the controllers to access directly abstract while continuing to contain method implementation.
Make the ServiceBase classes abstract with a protected constructor. Then only classes that derive from them can access their methods directly, forcing the controller to call the controllers service which then calls the base service classes.
I wrote all this up in a blog post here

What are good candidates for base controller class in ASP.NET MVC?

I've seen a lot of people talk about using base controllers in their ASP.NET MVC projects. The typical examples I've seen do this for logging or maybe CRUD scaffolding. What are some other good uses of a base controller class?
There are no good uses of a base controller class.
Now hear me out.
Asp.Net MVC, especially MVC 3 has tons of extensibility hooks that provide a more decoupled way to add functionality to all controllers. Since your controllers classes are very important and central to an application its really important to keep them light, agile and loosely coupled to everything else.
Logging infrastructure belongs in a
constructor and should be injected
via a DI framework.
CRUD scaffolding should be handled by
code generation or a custom
ModelMetadata provider.
Global exception handling should be
handled by an custom ActionInvoker.
Global view data and authorization
should be handled by action filters.
Even easier with Global action filters
in MVC3.
Constants can go in another class/file called ApplicationConstants or something.
Base Controllers are usually used by inexperienced MVC devs who don't know all the different extensibility pieces of MVC. Now don't get me wrong, I'm not judging and work with people who use them for all the wrong reasons. Its just experience that provides you with more tools to solve common problems.
I'm almost positive there isn't a single problem you can't solve with another extensibility hook than a base controller class. Don't take on the the tightest form of coupling ( inheritance ) unless there is a significant productivity reason and you don't violate Liskov. I'd much rather take the < 1 second to type out a property 20 times across my controllers like public ILogger Logger { get; set; } than introduce a tight coupling which affects the application in much more significant ways.
Even something like a userId or a multitenant key can go in a ControllerFactory instead of a base controller. The coupling cost of a base controller class is just not worth it.
I like to use base controller for the authorization.
Instead of decorating each action with "Authorize" attribute, I do authorization in the base controller. Authorized actions list is fetched from database for the logged in user.
please read below link for more information about authorization.
Good practice to do common authorization in a custom controller factory?
I use it for accessing the session, application data etc.
I also have an application object which holds things like the app name etc and i access that from the base class
Essentially i use it for things i repeat a lot
Oh, i should mention i don't use it for buisiness logic or database access. Constants are a pretty good bet for a base class too i guess.
I have used base controller in many of my projects and worked fantastic. I mostly used for
Exception logging
Notification (success, error, adding..)
Invoking HTTP404 error handling
From my experience most of the logic you'd want to put in a base controller would ideally go into an action filter. Action Filter's can only be initialized with constants, so in some cases you just can't do that. In some cases you need the action to apply to every action method in the system, in which case it may just make more sense to put your logic in a base as opposed to annotating every action method with a new actionFilter attribute.
I've also found it helpful to put properties referencing services (which are otherwise decoupled from the controller) into the base, making them easy to access and initialized consistently.
What i did was to use a generic controller base class to handle:
I created BaseCRUDController<Key,Model> which required a ICRUDService<TModel> object as constructor parameter so the base class will handle Create / Edit / Delete. and sure in virtual mode to handle in custom situations
The ICRUDService<TModel> has methods like Save / Update / Delete / Find / ResetChache /... and i implement it for each repository I create so i can add more functionality to it.
using this structure i could add some general functionality like PagedList / AutoComplete / ResetCache / IncOrder&DecOrder (if the model is IOrderable)
Error / Notification messages handling: a part in Layout with #TempData["MHError"] code and a Property in base Controller like
public Notification Error
{
set { TempData["MHError"] = value; }
get { return (Notification) TempData.Peek("MHError"); }
}
With this Abstract classes i could easily handle methods i had to write each time or create with Code Generator.
But this approach has it's weakness too.
We use the BaseController for two things:
Attributes that should be applied to all Controllers.
An override of Redirect, which protects against open redirection attacks by checking that the redirect URL is a local URL. That way all Controllers that call Redirect are protected.
I'm using a base controller now for internationalization using the i18N library. It provides a method I can use to localize any strings within the controller.
Filter is not thread safe, the condition of database accessing and dependency injection, database connections might be closed by other thread when using it.
We used base controller:
to override the .User property because we use our own User object that should have our own custom properties.
to add global OnActionExecuted logic and add some global action-filters

Can my ControllerActionInvoker be a singleton?

It doesn't seem like ControllerActionInvoker has any implementation details that require a new instance to be created for each Controller. It seems to have two properties with setters that are never used, and getters that are basically lazy references to static members.
I am considering changing the scope of my custom ControllerActionInvoker's life cycle in my ASP.NET MVC application. Is there a good reason I shouldn't do this? Is there something I'm missing about this class?
There isn't anything implicitly wrong with implementing the IActionInvoker this way.
However, there is also no implicit benefit. It depends on how you want to scope that particular component of the MVC lifecycle.

What's the best way to inject different implementations of the same interface in to a controller using StructureMap?

I am fairly new to StructureMap, but my understanding is that there are two ways of getting an instance from the ObjectFactory:
By type (i.e. ObjectFactory.GetInstance<IFoo>())
By type and name (i.e. ObjectFactory.GetNamedInstance<IFoo>("foo.bar"))
I have seen a multitude of examples out there demonstrating how to create an MVC Controller Factory that will provide controller instances using StructureMap, and in most cases I have seen, they are using the method from option #1 above.
Let's say we have some controller that accepts a repository/DAO interface as a constructor arg...
public class FooController : Controller
{
public FooController (IFooRepository fooRepository)
{
// constructor code goes here
}
}
Using the interface class gives me the ability to "inject" any implementation of that interface in to my controller. What if for two different actions, I want to inject different implementations? Perhaps in one case, I need an implementation of my repository that will query a SQL Server database, and in another case, I need an implementation that will get data from an XML file or through a Web Service call.
It seems that if you use the ObjectFactory.GetInstance() method, you would be restricted to only providing your controller with a single implementation of your repository interface.
However, if you go with named instances, then you will end up having to create the instances based on the name of the controller that the MVC framework provides. In most cases, this will typically be the controller name coming from the URL, but it's really up to the route configuration. This seems like it could be very confusing, and would only get more confusing as the number of routes increased.
Is there any alternative method that would allow for different controller instantiation strategies without using named instances? Would it be a better idea to just create separate controllers, and make sure that all the actions in any given controller will be valid for the same concrete instance of a repository/DAO class?
For what it's worth, I ended up going with named instances, where the names of each instance are based on the name of the controller that the MVC framework pulls from the URL.
For instance, the URL /foo/DoSomething might get an IController instance from the ObjectFactory that is instantiated with a Repository object that uses the SqlClient API for data access. A URL such as /foo.webservice/DoSomething would then create an instance of the same concrete controller class, but pass that instance's constructor a repository object that uses a web service for data access.
There are several ways to override StructureMap's default auto-wiring behavior for constructor arguments. In my case, I used the CtorDependency and Is methods, and had mappings that looked something like this...
// create a named instance for the "foo" controller that uses the SqlClient based repository
InstanceOf<IController>()
.Is.OfConcreteType<FooController>()
.CtorDependency<IFooRepository>()
.Is(new FooRepositorySql(Constants.FooConnectionString))
.WithName("foo");
// create a named instance for the "foo.webservice" controller that uses the Web Service based repository
InstanceOf<IController>()
.Is.OfConcreteType<FooController>()
.CtorDependency<IFooRepository>()
.Is(new FooRepositoryWs(Constants.FooServiceUrl))
.WithName("foo.webservice");

Access to Entity Manager in ASP .NET MVC

Greetings,
Trying to sort through the best way to provide access to my Entity Manager while keeping the context open through the request to permit late loading. I am seeing a lot of examples like the following:
public class SomeController
{
MyEntities entities = new MyEntities();
}
The problem I see with this setup is that if you have a layer of business classes that you want to make calls into, you end up having to pass the manager as a parameter to these methods, like so:
public static GetEntity(MyEntities entityManager, int id)
{
return entityManager.Series.FirstOrDefault(s => s.SeriesId == id);
}
Obviously I am looking for a good, thread safe way, to provide the entityManager to the method without passing it. The way also needs to be unit testable, my previous attempts with putting it in Session did not work for unit tests.
I am actually looking for the recommended way of dealing with the Entity Framework in ASP .NET MVC for an enterprise level application.
Thanks in advance
Entity Framework v1.0 excels in Windows Forms applications where you can use the object context for as long as you like. In asp.net and mvc in particular it's a bit harder. My solution to this was to make the repositories or entity managers more like services that MVC could communicate with. I created a sort of generic all purpose base repository I could use whenever I felt like it and just stopped bothering too much about doing it right. I would try to avoid leaving the object context open for even a ms longer than is absolutely needed in a web application.
Have a look at EF4. I started using EF in production environment when that was in beta 0.75 or something similar and had no real issues with it except for it being "hard work" sometimes.
You might want to look at the Repository pattern (here's a write up of Repository with Linq to SQL).
The basic idea would be that instead of creating a static class, you instantiate a version of the Repository. You can pass in your EntityManager as a parameter to the class in the constructor -- or better yet, a factory that can create your EntityManager for the class so that it can do unit of work instantiation of the manager.
For MVC I use a base controller class. In this class you could create your entity manager factory and make it a property of the class so deriving classes have access to it. Allow it to be injected from a constructor but created with the proper default if the instance passed in is null. Whenever a controller method needs to create a repository, it can use this instance to pass into the Repository so that it can create the manager required.
In this way, you get rid of the static methods and allow mock instances to be used in your unit tests. By passing in a factory -- which ought to create instances that implement interfaces, btw -- you decouple your repository from the actual manager class.
Don't lazy load entities in the view. Don't make business layer calls in the view. Load all the entities the view will need up front in the controller, compute all the sums and averages the view will need up front in the controller, etc. After all, that's what the controller is for.

Resources