i wind up having about 20 different parameters in the constructor of the model class, one for each service? Is this normal or a sign that something is off.
I think, categorically, that your controller is interacting with too many services. I've not seen your code - so I'm going off assumptions - but it seems to me that your controller is composing business logic by calling numerous "small" services, rather than drawing on fewer, "larger" services that compose business logic from the smaller services.
Have a look around for information about "orchestration services" vs "entity" or "capability" services and you'll see what I mean. If you create orchestration services that provide your controllers with the logic they require, your architecture is improved because your controllers really should not contain any business logic at all.
I really think that the number of services you consume is the issue here. IoC containers may go some way to resolve how you bind types to your injection parameters etc., but I think the problem is your architecture at this point.
You might try consolidating some services or think about refactoring the controller-view parts in to smaller scoped components. Also, a dependency injection style framework like Spring can help with things like this.
Allthough I don't know your setup. 20 seems a bit much I think you go against the SRP (Single responsibility priniciple). But since I can't see your code it is impossible to tell. If you really need all these services in that one model class then perhaps you need to put them in a factoryclass and use that as a parameter.
It is hard to give any good answer on this since we don't know your domain.
As #Matt said a dependency injection could help you here and sprint.NET is a good one and there are several others.
Seeing as you mention MVP in particular, you should at least look at Ent Lib 4.1 which now has Unity, Microsoft's take on DI. Their codeplex site is probably a good place to start if this is new.
There are also software factories that integrate with visual studio and give you tools for creating MVP for web sites as linked or web services. These come from pattern and practices too.
Related
I have been working on a MVC-EF application. We use DI container to inject dependencies into controllers, services, and repositories i.e across the UI-Services-DataAccess layers.
My question is regarding DI in services. One thing I have been confused about recently has been arisen from the need to use the behaviour (aka methods) that was implemented in one service in another service.
As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.
So my question is, how should I work this out?
Should I be implementing the needed behaviour in second service (as part of its own methods) or I can somehow reuse it from the already implemented first service?
Can DI container help me in this regard?
Or is it that the way out is to outsource behaviour implemented in services into a separate Business Logic Layer, so it is available to each of the services? BTW, we currently do not have a separate BLL.
As far as I know, one service should not take dependency upon another because that would finally be leading closer to circular dependency and hence causing issues for DI container down the line.
This isn't quite true. In general, your objects refer to each other, forming a graph. When we discuss Dependency Injection, we normally call it a Dependency Graph.
As long as this graph is a Directed Acyclic Graph, all is good. The keyword here is acyclic, but it doesn't preclude reuse. You can have several services that use a single instance of another service; that just means that the service is shared.
Dependency Graphs can be as shallow or as deep as required, as long as they are acyclic, you can compose dependency graphs with confidence.
As usual the answer is, "It depends", however based on what you have said regarding needing some behavior/method to be available to multiple services, I think the last approach you mentioned makes the most sense.
Creating an independent class for "Support" functions can be useful in a lot of scenarios, particularly if you have methods that are a used for several services. DI should then be able to help you provide the "Support" class to its dependents.
I would like to hear from you what are de the main advantages and drawbacks in applying dependency injection at the controller level, and/or domain level.
Let me explain; if I receive a IUserRepository as param for my User, I may proceed in two ways:
I inject IUserRepository direct on my domain object, then I consume User at controller level without newing objects, it means, I get them ready from the DI container.
I inject IUserRepository on my controller (say, Register.aspx.cs), and there I new all my domain objects using dependencies that came from the DI container.
Yesterday, when I was talking to my friend, he told me that if you get your domain objects from the container you loose its lifecicle control, as the container manages it for you, he meant that it could be error prone when dealing with large xml configuration files. Opinion which disagree as you may have a tests that loops through every domain object within an assembly and then asks the container whether thats a singleton, request scope, session scope or app escope. It fails if any of them are true. A way of ensuring that this kind of issue wont happen.
I fell more likely to use the domain approach (1), as I see a large saving on repetitive lines of code at controller level (of course there will be more lines at XML file).
Another point my friend rose was that, imagine that for any reason youre obligated to change from di container A to B, and say that B has no support for constructor injection (which is the case for a seam container, Java, which manipulates BC or only do its task via setter injection), well, his point is that, if I have all my code at controller level I'm able to refactor my code in a smoothly maner, as I get access to tools like Auto-Refactoring and Auto-Complete, which is unavailable when youre dealing with XML files.
Im stuck at this point, as I should have a decision to make right away.
Which approach should I leverage my architecture?
Are there other ways of thinking???
Do you guys really think this is a relevant concern, should I worry about it?
If you want to avoid an anemic domain model you have to abandon the classic n-tier, n-layer CRUDY application architecture. Greg Young explains why in this paper on DDDD. DI is not going to change that.
CQRS would be a better option, and DI fits very well into the small, autonomous components this type of architecture tends to produce.
I'm not into the Java sphere, but according to your details in your questions it seems like you use some kind of MVC framework (since you deal with Controllers and domain). But I do have an opinion about how to use DI in a Domain Driven architecture.
First there are several ways of doing DDD: Some uses MVC in presentation and no application service layer between MVC and Domain. Other uses MVP (or MVVM) and no service layer. BUT I think some people will agree on me that you very rarely inject repositories (or other services...). I would recommend to inject Repositories in Command (using MVC and no service layer), Presenter (if you use MVP) or Application Services (if you use service layer). I mostly use an application layer where each service get the repositories they need injected in constructor.
Second I wouldn't worry about switching between IoC containers. Most container framework today support ctor injection and can auto-resolve parameters. Now I know that you're a Java developer and I'm a MS developer, but MS Practices team has a Common Service locator that can helps you in producing code that are extremely non-dependent of which container framework you uses. There is probably some similar in the Java community.
So go for option 2. Hope I pushed you into right direction.
The question I'm asking is kind of subjective. I've seen twice, while exercising with real projects such as StoreFront, both Repository and Services. Sometimes they can just be folders or projects attached to the solution. But they contain classes and interfaces.
So, I'd like to know what goes to the repository and what goes to the services. So far, I was familiar with repositories (we put methods and properties in the repository to reduce the complexity in the controller). How about the services?
So, ASP.NET MVC: What's the difference in concept between Service and Repository? (Maybe none)
My question is Kind of subjective, but I'd like to make sure that I'm not missing anything.
Thanks for helping
Generally, the repository simply provides an interface to data. There is no application logic there. Services provide interfaces to application logic. Services often use repositories.
We are developing an application using Silverlight and WCF Services. Is using Spring.Net is beneficial for us?
>> "Is using Spring.Net is beneficial for us?"
I think the spirit of your question is really geared more towards questioning the benefit of using an IoC/DI framework versus manually managing dependencies as needed. My response will focus more on the why and why not of IoC/DI and not so much on which specific framework to use.
As Martin Fowler mentioned at a recent conference, DI allows you to separate configuration from usage. For me, thinking about DI in the light of configuration and usage as separate concerns is a great way to start asking the right questions. Is there a need for your application to have multiple configurations for your dependencies? Does your app need the ability to modify behavior by configuration? Keep in mind, this means that dependencies are resolved at runtime and typically require an XML configuration file which is nice because changes can be made without requiring a recompile of the assembly. Personally, I'm not a fan of XML-based configuration of dependencies as they end up being consumed as "magic strings". So there's the danger of introducing runtime errors if you end up misspelling a class name, etc. But if you need the ability to configure on-the-fly, this is probably the best solution today.
On the other hand, there are DI frameworks like Ninject and StructureMap that allow fluent in-code dependency definitions. You lose the ability to change definitions on-the-fly, but you get the added benefit of compile time validations, which I prefer. If all you want from a DI framework is to resolve dependencies then you could eliminate XML-based frameworks from the equation.
From a Silverlight perspective, DI can be used in various ways. The most obvious is to define the relationship of Views to ViewModels. Going deeper, however, you can define validation, and RIA context dependencies, etc. Having all of the dependencies defined in a configuration class keeps the code free from needing to know how to get/create instances and instead focus on usage. Don't forget that the container can manage the lifetime of each object instance based on your config. So if you need to share an instance of a type (e.g. Singleton, ManagedThread, etc.), this is supported by declaring the lifetime scope of each type registered with the container.
I just realized at this point I'm ranting and I apologize. Hope this helps!
Personally i'd recommend using either Castle or Unity as i've had great success with both and found them both, while different, excellent IOC frameworks.
Besides the IOC component they also provide other nifty tools (AOP in Castle, Interface interception in Unity, for example) which you will no doubt find a use for in the future, and having an IOC framework in place from the start is ALWAYS a hell of a lot easier than trying to retrofit it.
It's incredibly easy to setup and configure, although personally i'm not a huge fan of the XML config way of doing things as some of those config files can turn into a total nightmare. A lot of people will tell you that it's only worth doing if you intend to swap components in and out, but why not just do that anyway IN CASE you decide you need to do that later. it's better to have it and not use it, than not have it and need it. If you're worried about perf hit i've seen on many blog posts around the web people comparing the various IOC frameworks for their speed and unless you're creating brain surgery robots or the US Missile defence platform it won't be an issue.
A DI Framework might be of use if you want to change big chunks of your application without having to rewrite your constructors. For example, you might want to use a comet streaming service that you will expose through an interface, and later decide that you'd rather use a dedicated messenging system such as MQ or RendezVous. You will then write an adapter to Mq that respects the common facade and just change the spring config to use the Mq implementation rather than the Comet one.
But for the love of tony the pony, don't use Spring.Net to create your MVVM/MVP/MVC bindings for each and every view or you'll enter a world of pain.
DI is a great tool when used with parcimony, please don't end-up with 243 spring configuration files, for your devs' sanity.
Using an IOC container such as Spring.Net is beneficial as it will enable you to unit test parts of your UI by swapping in mocked or special test implementations of the applications interfaces. In the long run, this should make your application more maintainable for future developers.
I think if you do more in the code rather than using the markup to do bindings etc. and have a BAL/DAL DI can help there because it can inject the correct business component reference (as one example). DI has many other practical advantages, but then you have to do more in code and less in markup.
I was reading about DI thoroughly, and it seems interesting. So far, I'm totally living without it.
All the examples i saw are related to JNDI and how DI helps you being more flexible.
What is real life applications/problems that you solved with DI that will be hard to solve in other ways?
UPDATE
All the answers till now are educating, but to rephrase the question, I'm looking for examples in your programming life, that made you say "this problem will be best solved with a DI framework".
Just the other day, I decided to read up on dependency injection. Until then, I only knew the word. Honestly, my reaction to Martin Fowler's article was, "That's it?"
I have to agree with James Shore:
"Dependency Injection" is a 25-dollar term for a 5-cent concept.
That doesn't mean at all that it's a bad concept. But seriously, when an instance A needs to work with another instance B, it comes down to these choices:
let A find B:
That means B must be global. Evil.
let A create B:
Fine, if only A needs B. As soon as C also needs B, replace A by C in this list. Note that a test case would be a C, so if you do want to test, this choice is gone as well.
give B to A:
That's dependency injection.
Am I missing something? (Note that I'm from the Python world, so maybe there are language specific points I'm not seeing.)
Yesterday I found a mobile on the bus. The person who lost it had no clue about the person possessing her mobile. I called her dad and told him I have the mobile of his daughter. So I injected the dependency from me into him. Typically a case of the hollywood principle "Don't call us (because you can't!), we call you". Later he came and picked up his daughters phone.
I'd call that a real world problem which I solved by dependency injection, isn't it?
In my opinion, DI is not THE way to solve problems, for which we would not have another solution. Factories can be another way to solve such problems.
So there is no real answer for your question, because DI is just one way besides others. It is just a pretty hip, although very elegant way.
I really enjoyed DI when I had this DAOs, which needed an SQLMapper. I just had to inject the different mappers into the fatherclass once and the rest was done by configuration. Saved me a lot of time and LOCs, but I still can't name this a problem for which there is no other solution.
I use dependency injection for testing all the time. It's also extremely helpful when you have a bunch of large systems that you do not want to directly tie together (extremely loose coupling).
If you're using Java, I would recommend Google Guice, since it rocks so much. For C++, I recommend Qt IOC. For .NET, the Castle Project provides a nice IOC system. There is also a Spring implementation basically everywhere, but that's boring.
DI allows you to create applications that can be configured and reconfigured without touching the codebase itself. Not just urls or settings though; generic objects can be written in code, and then "customized" or configured via XML files to achieve the specific result desired for the given case.
For example, I can create a RegexDetective class where the actual regex it looks for is provided in a setter, and then in my Spring DI XML file, define one actual regex expression for RegexDetective.setRegex() for a deployment of SleuthApp going to London. Then a few days later I can go back and update the regex in the XML file for another deployment of SleuthApp shipping out to Siberia.
DI also allows one to define specific implementations of interfaces in a similar fashion, outside of the codebase in XML, to modify behavior of an application without actually touching the code, such as setting the AngryDetective or ArcticDetective implementation of the Detective interface, in the DI XML file.
We run a multimedia service for different countries. We run the same code for everyone but sometimes, business rules are different from one country to another. In this case, we inject different Spring MVC Interceptor for one client or for another.
Then, in the deploy phase, a script "chooses" which DI file is needed, based on the last letters of the files (fr for France, ch for Switzerland etc...)
application-context.xml-fr
application-context.xml-ch
etc...
That's the only good use I see in DI. I'm not a fan of DI though.
I've used Spring's IoC (DI) container for the last three web apps I've developed. I don't think its suited to one particular type of problem, rather it's a different way of solving a problem. It's as you've said, a more flexible approach to large systems. My personal favourite features of DI are that you can prepare better unit tests because your classes are highly decoupled. Also important for me is code reuse. Since I use the container in many apps, I can use the same components and know that their dependencies will be fed in externally.
In large multi-module applications using DI, a module only depends on the interfaces on the collaborator of its classes, which cuts compile-time dependency graphs.
In the context of frameworks (calling "your" functional code, as opposed to functional code calling a library), this is required. Your code can have compiling dependencies to the framework, but we all know that the framework (out of your hands) could not have compile dependencies to your code ;-)
I use DI primarily for ease of testing. Additionally it fosters the model of stubbing out your service calls to provide isolation and the ability to implement independent of service development.