I've not looked at the AutoMapper source code yet but was just about to make some changes to an API controller in my solution and had a thought.
The way I like to code is to keep my controller methods as concise as possible, for for instances I make use of a generic Exception attribute to handle try{}catch{} scenarios.
So only the code that is absolutely relevant to the controller action is actually in the action method.
So I just arrived at a situation where I need to create an AutoMapper map for a method. I was initially thinking that I would add this (as I have done previously) to the controller constructor so its available immediately.
However, as the controller grows following this pattern may introduce a lot unnecessary AutoMapper work depending on the controller action method which is invoked.
Considering controllers are created and destroyed per request this could get expensive.
What are some recommendations around this? Considering AutoMapper is accessed statically I was wondering if it's internals live beyond the request lifetime and it internally checks for an existing map before creating a new one each time CreateMap() is invoked?
You should create your maps (CreateMap) once per AppDomain, ideally when this domain starts (Application_Start).
Related
I'm trying to decide, according to Grails best practices and MVC patterns, when is the correct time to introduce a Service and not keep fattening controllers. I find it somewhat conflicting, what I've read about best practices and what appears to be common practice, so would love to hear what others think about this.
With GORM calls in mind, I would have expected that anything to do with GORM should really go into a service. Although I don't practice this myself, especially when writing very basic controller methods like show that simply perform a get() on a domain class and then render a view to show the details of the retrieved object.
However, after following books like 'Clean Code' and similar books, well maintained code should be cohesive and methods should ideally perform a single task only. So in the perfect world, would the show method in a controller be responsible only for determining the object to display before rendering a view? The retrieval from the database could go into a method in the database that's sole task is to retrieve from the DB and throw an exception if not found etc.
But yes, this does somewhat seem like overkill.
So taking the step a bit further, the create() or update() methods. Again currently Grails' generated code puts everything into the controller, no use of a service at all.
So when would the recommended point be that we need to use a Service? Is it only when something transactional has to take place, for instance, on a create() call, we might also want to write a record to a Log file to keep an audit log of sorts. Surely this warrants a service?
I'd love to hear what others feel is the correct time to introduce services, I imagine it differs greatly person to person.
I recommend you this post: http://www.infoq.com/articles/grails-best-practices
We are creating static methods in Domain class to encapsulate queries. Service are used only for transactional operations or very complex queries with multiple domains interaction. Controllers simply call domains or services methods.
Say I have a core data model with a few entities and, throughout the application's lifecycle, I'll be getting and setting properties of these entities from different views.
At least to me, it seems like passing the managed object context around from view controller to view controller and having the controller's code know about the different entities or derived objects goes against decoupling. As a matter of fact, there is a similar question where the only answer suggests passing around the managed object context.
So, in the spirit of MVC, I thought it might make more sense for view controllers to stick to controlling views, and have a singleton model controller through which these view controllers can query the model to feed their views and notify back when the model needs to be updated based on user interaction with the view.
But I'm not sure how to go about implementing the single model controller interface. For instance, here's a few ideas:
make this controller both a delegate and data source to all view controllers?
have the controller be only a data source and use notifications for updates?
kvc/o?
is the whole idea of a centralized bridge from/to the model just overengineering the MVC pattern? That is, is there some reasonable argument in favor of instead passing the managed context around and this not being considered crappy object-oriented design?
Another thing I'm thinking is, if the singleton controller is a delegate and data source, the methods to get model data and update the model should implement some sort of visitor pattern, right? Meaning, for example, if view controller A allows the user to interact with model entity / object A and some view controller B allows for the same for a model object B, and both view controllers rely on the same delegate, the delegate will have to have some way to know which model entity it should target depending on what concrete controller is calling on it.
I'd appreciate any thoughts / ideas
Your idea of a "model controller" makes sense, the problem is I think you may be thinking of it wrong.
It's not really a "model controller," it is the model. In MVC (traditionally), the views communicate with their controller for advice on what to do with interactions, and the controller decides what to tell them based on its logic and information it gathers from the model.
So really, you're simply abstracting the model further, which is a good thing. The idea of a "centralized bridge" is what you want in MVC. Your controller should see a high-level abstraction of the underlying model's implementation, as with all interfaces and layers of abstraction.
As far as implementing the model goes, I'm not sure which is the "best" way to do it, but I can't imagine using the delegate/data source strategy (or sending notifications to the controller) would be detrimental, I'd guess it depends on what you're comfortable with. If you love KVC/KVO, I doubt it'll hurt you. As far as the visitor pattern goes, the logic concerning keeping track of which controller gets which object should be within the model.
It seems to me that your biggest concern is with passing the model around from controllers. It is perfectly alright for the controllers to reference and use the model, but trying to manage their creation and penetration, you're right, is a bit much.
I'd recommend using a Dependency Injection container that can generate the access layer to your model. This way the controllers will get the model passed to them via DI, w/o having to pass around how to create the model classes.
The idea of a single centralized bridge isn't a bad one either, but it would make things a little tricky to unit test.
In the end, I ended up dropping the delegate / datasource approach for a singleton pattern:
I figured the following:
all controllers are collaborating with a single shared
managedObjectContext
the Core Data model itself revolves around a single "configuration"
entity (not the configurations that the Core Data literature refers
to).
This "default configuration" is also what all controllers interact
with, since all other entities exist in the context of this
configuration entity.
So essentially, I have a shared resource which should be accessible in a way similar to a global variable.
So I encapsulated the shared resource in a Singleton through whose interface all other controllers can query and modify the model without knowing much about the internals.
The general interface allows for things like:
[ModelControllerBridge sharedBridge] defaultConfiguration] which
returns the default shared NSManagedObject
[[ModelControllerBridge sharedBridge] newDataSample] which returns a
new NSManagedObject and internally allocates and inserts it in the
appropriate entity within the model.
[[ModelControllerBridge] shouldCommitChangesToModel] which signals
the context should be committed to the permanent store
etc.
I'm writing my first MVC (v3) app and I think I've organized my controllers incorrectly. I'd appreciate some guidance/advice.
This all came up because I'm using Ninject for dependency injection, and wanted it to create only one instance of my concrete DataRepository for each "request". That's easy enough to do by specifying InRequestScope() in the Ninject bindings...but after doing that I still kept seeing multiple instances of my DataRepository being created.
After scratching my head for quite a while I started monitoring the BeginRequest event in the MvcApplication class (in the global.asax file). Lo and behold, what I had thought of as a single "request" -- e.g., a single postback from the browser -- was in fact yielding multiple consecutive requests. Ninject, as per the InRequestScope() declaration, dutifully created one instance of my DataRepository for each of those requests.
Unfortunately, that's not quite what I want. What I'd like is one instance of the DataRepository being created for that single browser-initiated "request". I don't see how I can do this via Ninject. I know I could specify InSingletonScope(), but while that will utilize one DataRepository instance for the "request", the instance will hang around until the webapp restarts. Which causes me all sorts of Entity Framework caching issues.
In monitoring the BeginRequest events, it looks to me like every time a different controller is called a new request is generated. In hindsight this makes sense, but it's not consistent with my app's design. For example, I have certain common action methods that various other action methods chain to (I did that rather than duplicate the same code and views in different controllers).
All of which leads me to wonder about the following: if I want to minimize the number of times my DataRepository is instantiated I have to minimize the number of times one controller chains to another controller. Which would seem to mean that my action methods need to be consolidated, and possibly duplicated in multiple controllers.
That seems... odd. If it's the right way to do things, okay, I can live with it. But I'd love to learn that I'm missing something else in the way of designing MVC apps :). Should I, for example, centralize those common functions in a service layer, and only instantiate it once per request? If that's a dumb question, apologies; I don't really understand the concept of a service layer.
Regarding your last question: It is always better to keep the controllers free of any business logic. Their main purpose is to manage its view. Any business logic belongs to a proper business layer.
Also I think it's a good design not to reuse the repository instances too intensively. Any transaction should use its own instance. See "Unit of Work". In most cases this means one instance per request. Repositories of readonly data such as a product catalog can be reused of course by declaring them in singleton scope.
See: http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx
i have several controllers which will all be using common functionality. So i have separated that functionality into a separate controller.
the shared controller needs a parameter specific to which controller it is being used from, and needs to return views based on id ints passed to it.
So, one idea is to create an instance of SharedController(int callingControllerId) in the constructor of each of the controllers that will be using it. Then, within the action methods of each controller, call the action methods of the shared controller, passing appropriate ids, and returning views from SharedController to the calling controller, which would return the view to be rendered.
Does this sound right? Should controllers be creating other controllers in MVC?
Thanks!
Absolutely not although having your controller inherit from a shared, base controller is pretty common.
public KittyController : MySharedBaseController
{
}
Like Greg Roberts points out that although having a ControllerBase is common it is not always the best place to store shared functionality. MVC has a lot of extensibility points and picking a narrow place to wedge in your code is a lot better than smushing tons of things into a base controller.
I would agree that a base controller is pretty common, but I'm not sure it's the right solution for what you are describing.
Without knowing what is exactly shared it's a bit hard to figure out, but the whole bit of your base controller knowing specifics about the controllers that are inheriting from it smells a bit.
Here are a couple things to consider.
Composition is almost always better than inheritance. Great article on this
Base controller should have common methods/properties, for example mine have some properties of getting the current user and a generic method for calling external services, but not specific things from inheriting controllers. Rule of thumb, if it's not needed by more than 1 controller, than probably not good in base implementation.
It's possible that some of the new MVC 2 features might solve what you are doing. Look at render action.
As with anything in software, there are tons of ways to solve the problem, so ultimately do it the way that makes the most sense to you and your team.
Controllers are constructed by the ASP.NET MVC runtime and you should never be constructing them in your own code. It sounds like you don't really need a separate controller, you just need another class that you aggregate in the controller, and use as a service. This is perfectly acceptable. In fact, I would go so far as to say that in general controller should be delegating their work to other "service" classes and shouldn't have much responsibility (especially domain logic) in and of themselves.
I don't know the details of why this service class needs to know what controller it is being called from, but perhaps you can just declare an enum that defines the different use cases, and pass that in in its constructor. Actually having the service class know about different controllers would be a code smell for me.
I'm considering strategies for a simple-minded CMS implementation for an ASP.NET MVC site. The simple-minded part is that I've abstracted the values used in various partial views, all of which are user controls that share identical CSS layouts. So I'm populating the custom values in the identical partial views from the database where I can modify them occasionally using CRUDs.
The not so simple part is a reasonably efficient and logical abstraction of a standard UI element as a sql table row. But putting that aside...
I know I'm going to use some super-models to hand to each page the pre-configged models for the partial views. But if they are pre-configged and pre-loaded, where to put them until called?
The part that makes me think I'm a little insane to go this way is the load time for what is essentially static data. But then again, SharePoint!
So (I think) why not load it all in application_start? Why not? I answer! Then I get to use IoC for something that google returns not one link to good information from even one smart person who has ever considered that it might be a sane idea.
So does anyone have a better idea for populating a Model from the database using an IoC container other than putting a repository call in the constructor?
And then, does anyone think that putting these static-data models in an IoC container accessible to the controllers is a dumb idea?
Thanks,
S. Machino
Following several SOLID principles, keep your stuff as single-minded as possible. For semi-static data, first create a Repository that loads this data. This will load the data for every request. It works, but probably doesn't perform so well, but now you have the implementation you need.
The next thing you can do is to Decorate the first Repository with a caching Repository. This CachingRepository will read from the decorated Repository only once, and then keep data in memory.
Thus you respect Separation of Concerns.
If you scope the CachingRepository instance to be a Singleton, it will live until the application is recycled, effectively keeping the cached data in memory.
You may want to consider using the OutputCache attribute in your design. You can decorate your action methods that will return static data with this attribute and the framework will take care of caching.
Of course, you still need to handle when to invalidate the cache.