Dependency-injection called too many times? - asp.net-mvc-3

ok, maybe I am missing something or worried to much...
I have a controller that generates my images. On a page it could have 100 or more images. For every image that is generated, the ImagingController is called.
I use dependency injection and notice that for every image that is displayed, the dependent classes are constructed.
src="#Url.Action("Thumbnail", "Imaging")/id"
private readonly IDBAccess _dbaccess;
private readonly ILogger _logger;
private readonly ISettings _settings;
private readonly IStateManager _statemanager;
public ImagingController(IDBAccess dbaccess, ILogger logger, ISettings settings, IStateManager statemanager)
{
this._dbaccess = dbaccess;
this._logger = logger;
this._settings = settings;
this._statemanager = statemanager;
}
public ActionResult Thumbnail(int id)
{
...
return File((byte[])data, "image/jpeg");
}
So every of the above 4 dependent classes are constructed 100 times. This seems a bit too much overhead or am I wrong?

It's possible to optimize this using lifetime management. If one or more of the dependencies are thread-safe, there's no reason to create a new instance for every request. Instead, you can reuse the same instance for all 100 requests.
This is called the Singleton lifetime style (not to be confused with the Singleton design pattern).
You don't write if you use a DI Container, or wire dependencies up by hand, so for details on how to do this, I'll refer you to my book, which both explains how to do it manually, and how to configure lifetimes for 6 different DI Containers.
In addition, you may also find this article useful: http://blog.ploeh.dk/2011/03/04/Composeobjectgraphswithconfidence

Related

ZK & Spring - Safe to use Executions.getCurrent() in Spring Bean?

I want to create a utility Bean for common URL parsing in my ZK Composers. However, I want to make sure it is safe to use things like Executions.getCurrent() in a Spring managed Bean. I'm pretty sure it is as Executions.getCurrent() is static to begin with.
Here's what I'm thinking of doing..
#Component
public MyUrlBean {
// TODO I will, of course, program to an interface here =)
private static final String MY_OBJECT_URL_PARAMETER = "my_obj";
public MyObject getMyObjectFromURL() {
Execution ex = Executions.getCurrent();
String value = ex.getParameter(MY_OBJECT_URL_PARAMETER)
// ... db fetch and the like
}
}
..used like so..
#VariableResolver(DelegatingVariableResolver.class)
public MyComposer extends SelectorComposer<Window> {
#WireVariable
public MyUrlBean myUrlBean;
#Override
public void doAfterCompose(Window component) {
MyObject myObject = myUrlBean.getMyObjectFromURL();
// ...
}
}
So, doing things this way, should everything work fine or should I anticipate problems with user sessions clashing or the like?
Spring beans are NOT static singletons, correct? Instead they are instance classes that are autowired to save computation time of actually newing up objects, correct? If that is the case then there definitely won't be clashes between users like this.
Anyway, as I mentioned, Executions.getCurrent() is static. Hmm, how does that work with multiple users accessing a webapp?
Yes, it's safe.
I don't have much official sources to link here, but for what it's worth, my previous team has been using this in almost every page (to get a user context) of an app serving over 3000 users in production with no recorded problem in two years.

Using TDD approach and avoiding Java static methods

I just got some feedback about a job application Java coding exercise. They did not like the solution and two problems where stated in the feedback (which I'm very grateful for as it's very rare feedback is given):
I did not use TDD approach, apparently.
I overused static methods, I know static methods are anti OO but I only used them in validation and util type methods.
So two questions here:
What are the possible tell-tale signs of not using TDD approach?
What coding style or patterns can be an alternative to static methods?
Following the first two responses I have another question.
Do you agree that using static methods is only bad when it limits the testability of your code and not in them selves bad.
So going back to my job application exercise solution if the static methods do not limit the testability of my code is it still bad to use? my validate method was very simple 'Validator.notNull(p,"paramName")' now why would I ever want to mock that?
Many thanks.
A tell-tale sign of not using TDD is usage of static methods and static class members for collaborators. You cannot override a static method, so you cannot substitute a mock to test the class using such methods in isolation.
Instead of using static collaborators or static methods on the collaborators, you can use dependency injection. In a simple coding exercise you would inject dependency via a constructor or via the setters by hand. In the real life you can use one of available dependency frameworks.
Your static Validaton method seems something that should be part of an object to me.
Say you have an class Drink
public class Drink
{
private readonly string _name;
private readonly double _temperature;
public Drink(string name, double temperature)
{
_name = name;
_temperature = temperature;
}
}
Your businesslogic would be able to instantiate all kinds of drinks, 7up, cola, whatever. You'd like to make sure that a drink has the appropriate temperature to drink it, so you have the need for a Validate method. You could follow your approach:
public void TakeAZip()
{
if (Validation.HasAppropriateTemp)
{
// implement drink
}
}
'
Alternatives for static classes
That way you have an hard dependency on your static Validation class.
Alternatively you could make use of dependency injection.
public void TakeAZip(ITemperatureValidator validator)
{
if (validator.HasAppropriateTemp)
{
// implement drink
}
}
If more convenient you could also choose to pass the Validator via the constructor
private readonly string _name;
private readonly double _temperature;
private ITemperatureValidator _validator;
public Drink(
string name,
double temperature,
ITemperatureValidator validator)
{
_name = name;
_temperature = temperature;
_validator = validator;
}
Now you can mock the behavior of your validator and you can isolate your Drink class from all external behavior.

How to inject ISession into Repository correctly?

Please correct me on the following scenario. ( Question is at the end)
(I asked a similar question that was un-organized and it was voted to close. So I have summarized the question here into a scope that can be replied with exact answers.)
I am developing a web application with multiple layers using nhibernate as ORM. My layer structure is as follow
Model Layer
Repository Layer
Services Layer
UI Layer
with the above layers, the classes and interfaces are placed as below.
ProductController.cs (UI Layer)
public class ProductController : Controller
{
ProductServices _ProductServices;
NHibernate.ISession _Session;
public ProductController()
{
_Session = SessionManager.GetCurrentSession();
_ProductServices = new ProductServices(
new ProductRepository(), _Session);
}
// Cont..
}
ProductServices.cs (Service Layer)
public class ProductServices : IProductServices
{
protected IProductRepository _ProductRepository;
protected NHibernate.ISession _Session;
public ProductServices(IProductRepository productRepository,
NHibernate.ISession session)
{
_ProductRepository = productRepository;
_Session = session;
_ProductRepository.SetSession(_Session);
}
// cont...
}
ProductRepository.cs (Repository Layer)
public class ProductRepository : IProductRepository
{
NHibernate.ISession _Session;
public void SetSession(NHibernate.ISession session)
{
_Session = session;
}
public IEnumerable<Product> FindAll()
{
return _Session.CreateCriteria<Product>().List<Product>();
}
//cont..
}
From the UI layer, I create the session as request per session and inject into service layer with the help of class constructor. Then set the session of repository with a help of a method.
I am afraid if I pass the _Session directly to repository as constructor, I will not have the control over it under the service layer. Also there is a future extension plan for using a webservice layer.
** Is there a way to ensure in each method of ProductRepository class that _Session is set already, without writing the piece of code if(_Session==null) in each and every method as it is repeating the same code.
** If the above pattern is wrong, Please show me a right way to achieve this goal.
What you are doing amazed me a bit. You applying the constructor injection pattern in the ProductService, which is definitely the way to go. On the other hand you are not injecting the dependencies into the ProductController, but that class is requesting one of those dependencies through a static class (this is the Service Locator anti-pattern) and creates a ProductServices class itself. This makes this class hard to test and makes your application less flexible and maintainable, since you can't easily change, decorate or intercept the use of the ProductServices class, when it's been used in multiple places.
And although you are (correctly) using constructor injection for the dependencies in the ProductServices, you are passing those dependencies on to the product repository, instead of applying the constructor injection pattern on the ProductResopistory as well.
Please show me a right way to achieve this goal.
The right way is to apply the constructor injection pattern everywhere. When you do this, your code will start to look like this:
public class ProductController : Controller
{
private ProductServices _ProductServices;
public ProductController(ProductServices services)
{
_ProductServices = services;
}
// Cont..
}
public class ProductServices : IProductServices
{
private IProductRepository _ProductRepository;
public ProductServices(
IProductRepository productRepository)
{
_ProductRepository = productRepository;
}
// cont...
}
public class ProductRepository : IProductRepository
{
private ISession _Session;
public ProductRepository (ISession session)
{
_Session = session;
}
public IEnumerable<Product> FindAll()
{
return _Session
.CreateCriteria<Product>().List<Product>();
}
//cont..
}
See how each class only takes in dependencies that it uses itself. So the ProductController and ProductServices don't depend on ISession (I made the assumption that only ProductRepoistory needs ISession). See how -from a class's perspective- everything is much simpler now?
Did we actually solve a problem here? It seems like we just moved the problem of wiring all classes together up the dependency graph. Yes we did move the problem. And this is a good thing. Now each class can be tested in isolation, is easier to follow, and the application as a whole is more maintainable.
Somewhere in the application however, a ProductController must be created. This could look like this:
new ProductController(
new ProductServices(
new ProductRepository(
SessionManager.GetCurrentSession())));
In its normal configuration, ASP.NET MVC will create controller classes for you, and it needs a default constructor to do so. If you want to wire up controllers using constructor injection (which you should definitely do), you need to do something 'special' to get this to work.
ASP.NET MVC allows you to override the default ControllerFactory class. This allows you to decide how to create controller instances. However, when your application starts to grow, it will get really awkward very quickly when you are creating your dependency graphs by hand (as my last example shows). In this case, it would be much better to use a Dependency Injection framework. Most of them contain a feature / package that allows you to integrate it with ASP.NET MVC and automatically allows to use constructor injection on your MVC controllers.
Are we done yet? Well... are we ever? There's one thing in your design that triggered a flag in my brain. Your system contains a class named ProductServices. Although a wild guess, the name Services seems like you wrapped all product related business operations inside that class. Depending on the size of your system, the number of people on your team, and the amount of changes you need to make, this might get problematic. For instance, how to you effectively apply cross-cutting concerns (such as logging, validation, profiling, transaction management, fault tolerance improvements) in such way that to system stays maintainable?
So instead of wrapping all operations in a single ProductServices class, try giving each business transaction / use case its own class and apply the same (generic) interface to all those classes. This description might be a bit vague, but it is a great way to improve the maintainability of small and big systems. You can read more about that here.
You can use a dependency injection container such as Autofac to instantiate your session and manage the lifetime of it. Leave the responsibility of instantiating the session to Autofac and simply inject the ISession interface into any classes that require the dependency. Have a look at this post: Managing NHibernate ISession with Autofac
You will also find this wiki page useful about configuring Autofac with MVC3: http://code.google.com/p/autofac/wiki/MvcIntegration3

How to reduce number of injected dependencies on controller

I am using MVC3, Entity Framework v4.3 Code First, and SimpleInjector. I have several simple classes that look like this:
public class SomeThing
{
public int Id { get; set; }
public string Name { get; set; }
}
I have another entity that looks like this:
public class MainClass
{
public int Id { get; set; }
public string Name { get; set; }
public virtual AThing AThingy { get; set; }
public virtual BThing BThingy { get; set; }
public virtual CThing CThingy { get; set; }
public virtual DThing DThingy { get; set; }
public virtual EThing EThingy { get; set; }
}
Each Thingy (currently) has its own Manager class, like so:
public class SomeThingManager
{
private readonly IMyRepository<SomeThing> MyRepository;
public SomeThingManager(IMyRepository<SomeThing> myRepository)
{
MyRepository = myRepository;
}
}
My MainController consequently follows:
public class MainController
{
private readonly IMainManager MainManager;
private readonly IAThingManager AThingManager;
private readonly IBThingManager BThingManager;
private readonly ICThingManager CThingManager;
private readonly IDThingManager DThingManager;
private readonly IEThingManager EThingManager;
public MainController(IMainManager mainManager, IAThingManager aThingManager, IBThingManager bThingManager, ICThingManager cThingManager, IDThingManager dThingManager, IEThingManager eThingManager)
{
MainManager = mainManager;
AThingManager = aThingManager;
BThingManager = bThingManager;
CThingManager = cThingManager;
DThingManager = dThingManager;
EThingManager = eThingManager;
}
...various ActionMethods...
}
In reality, there are twice as many injected dependencies in this controller. It smells. The smell is worse when you also know that there is an OtherController with all or most of the same dependencies. I want to refactor it.
I already know enough about DI to know that property injection and service locator are not good ideas.
I can not split my MainController, because it is a single screen that requires all these things be displayed and editable with the click of a single Save button. In other words, a single post action method saves everything (though I'm open to changing that if it makes sense, as long as it's still a single Save button). This screen is built with Knockoutjs and saves with Ajax posts if that makes a difference.
I humored the use of an Ambient Context, but I'm not positive it's the right way to go.
I humored the use of injecting a Facade as well.
I'm also wondering if I should implement a Command architecture at this point.
(Don't all of the above just move the smell somewhere else?)
Lastly, and perhaps independent of the three above approaches, is should I instead have a single, say, LookupManager with explicit methods like GetAThings(), GetAThing(id), GetBThings(), GetBThing(id), and so on? (But then that LookupManager would need several repositories injected into it, or a new type of repository.)
My musings aside, my question is, to reiterate: what's a good way to refactor this code to reduce the crazy number of injected dependencies?
Using a command architecture is a good idea, since this moves all business logic out of the controller, and allows you to add cross-cutting concerns without changes to the code. However, this will not fix your problem of constructor over-injection. The standard solution is to move related dependencies into a aggregate service. However, I do agree with Mark that you should take a look at the unit of work pattern.
Have you considered using a unit of work design pattern? There is a great MSDN post on what a unit of work is. An excerpt from that article:
In a way, you can think of the Unit of Work as a place to dump all
transaction-handling code. The responsibilities of the Unit of Work
are to:
Manage transactions.
Order the database inserts, deletes, and updates.
Prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice
object as changed, but the Unit of Work class will only issue a
single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of your
code from these concerns so that you can otherwise concentrate on
business logic.
There are several blog posts about this, but the best one I've found is on how to implement it is here. There are some other ones which have been referred to from this site here, and here.
Lastly, and perhaps independent of the three above approaches, is
should I instead have a single, say, LookupManager with explicit
methods like GetAThings(), GetAThing(id), GetBThings(), GetBThing(id),
and so on? (But then that LookupManager would need several
repositories injected into it, or a new type of repository.)
The unit of work would be able to handle all of these, especially if you're able to implement a generic repository for most of your database handling needs. Your tag mentions you're using Entity Framework 4.3 right?
Hope this helps!
I think your main issue is too many layers of abstraction. You are using Entity Framework, so you already have a layer of abstraction around you data, adding two more layers (one per entity) via a Repository and a Manager interface has led to the large number of interfaces your controller depends upon. It doesn't add a whole lot of value, and besides, YAGNI.
I would refactor, getting rid of your repository and manager layers, and use an 'ambient context'.
Then, look at the kinds of queries your controller is asking of the manager layers. Where these are very simple, I see no problems querying your 'ambient context' directly in your controller - this is what I would do. Where they are more complicated, refactor this into a new interface, grouping things logically (not necessarily one per Entity) and use your IOC for this.

Using DI to cache a query for application lifetime

Using a DI container (in this case, Ninject) is it possible - - or rather, wise to cache a frequently used object for the entire application lifetime (or at least until it is refreshed)?
To cite example, say I have a Template. There are many Template objects, but each user will inherit at least the lowest level one. This is immutable and will never change without updating everything that connects to it (so it will only change on administration demand, never based on user input). It seems foolish to keep querying the database over and over for information I know is not changed.
Would caching this be best done in my IoC container, or should I outsource it to something else?
I already store ISessionFactory (nHibernate) as a Singleton. But that's a little bit different because it doesn't include a query to the database, just the back-end to open and close ISession objects to it.
So basically I would do something like this..
static class Immutable
{
[Inject]
public IRepository<Template> TemplateRepository { get; set; }
public static ITemplate Template { get; set; }
public void Initialize()
{
if(Immutable.Template == null)
{
Immutable.Template = TemplateRepository.Retrieve(1); // obviously better logic here.
}
}
class TemplateModule : Module
{
public void Load()
{
Bind<ITemplate>().ToMethod(() => Immutable.Initialize())InSingletonScope();
}
}
Is this a poor approach? And if so, can anyone recommend a more intelligent one?
I'd generally avoid using staticness and null-checking from your code - create normal classes without singleton wiring by default and layer that aspect on top via the container. Ditto, remove reliance on property injection - ctor injection is always better unless you have no choice
i.e.:
class TemplateManager
{
readonly IRepository<Template> _templateRepository;
public TemplateManager(IRepository<Template> templateRepository)
{
_templateRepository = templateRepository;
}
public ITemplate LoadRoot()
{
return _templateRepository.Retrieve(1); // obviously better logic here.
}
}
class TemplateModule : Module
{
public void Load()
{
Bind<ITemplate>().ToMethod(() => kernel.Get<TemplateManager>().LoadRoot()).InSingletonScope();
}
}
And then I'd question whether TemplateManager should become a ninject provider or be inlined.
As for the actual question... The big question is, how and when do you want to control clearing the cache to force reloading if you decided that the caching should be at session level, not app level due to authorization influences on the template tree? In general, I'd say that should be the Concern of an actual class rather than bound into your DI wiring or hardwired into whether a class is a static class or is a Singleton (as in the design pattern, not the ninject Scope).
My tendency would be to have a TemplateManager class with no static methods, and make that a singleton class in the container. However, to get the root template, consumers should get the TemplateManager injected (via ctor injection) but then say _templateManager.GetRootTemplate() to get the template.
That way, you can:
not have a reliance on fancy ninject providers and/or tie yourself to your container
have no singleton cruft or static methods
have simple caching logic in the TemplateManager
vary the Scoping of the manager without changing all the client code
have it clear that getting the template may or may not be a simple get operation
i.e, I'd manage it like so:
class TemplateManager
{
readonly IRepository<Template> _templateRepository;
public TemplateManager(IRepository<Template> templateRepository)
{
_templateRepository = templateRepository;
}
ITemplate _cachedRootTemplate;
ITemplate FetchRootTemplate()
{
if(_cachedRootTemplate==null)
_cachedRootTemplate = LoadRootTemplate();
return _cachedRootTemplate;
}
ITemplate LoadRoot()
{
return _templateRepository.Retrieve(1); // obviously better logic here.
}
}
register it like so:
class TemplateModule : Module
{
public void Load()
{
Bind<TemplateManager>().ToSelf().InSingletonScope();
}
}
and then consume it like so:
class TemplateConsumer
{
readonly TemplateManager _templateManager;
public TemplateConsumer(TemplateManager templateManager)
{
_templateManager = templateManager;
}
void DoStuff()
{
var rootTempalte = _templateManager.FetchRootTemplate();
Wild speculation: I'd also consider not having a separate IRepository being resolvable in the container (and
presumably having all sorts of ties into units of work). Instead, I'd have the TemplateRepository be a longer-lived thing not coupled to an ORM layer and Unit Of Work. IOW having a repository and a Manager none of which do anything well defined on their own isnt a good sign - the repository should not just be a Table Data Gateway - it should be able to be the place that an Aggregate Root such as Templates gets cached and collated together. But I'd have to know lots more about your code base before slinging out stuff like that without context!

Resources