As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Google Guice provides some great dependency injection features.
I came across the #Nullable feature recently which allows you to mark constructor arguments as optional (permitting null) since Guice does not permit these by default:
e.g.
public Person(String firstName, String lastName, #Nullable Phone phone) {
this.firstName = checkNotNull(firstName, "firstName");
this.lastName = checkNotNull(lastName, "lastName");
this.phone = phone;
}
https://github.com/google/guice/wiki/UseNullable
What are the other useful features of Guice (particularly the less obvious ones) that people use?
None of 'em are intended to be hidden, but these are my favorite 'bonus features' in Guice:
Guice can inject a TypeLiteral<T>, effectively defeating erasure.
TypeLiteral can do generic type resolution: this tells you that get() on a List<String> returns an Iterator<String>.
Types is a factory for implementations of Java's generic type interfaces.
Grapher visualizes injectors. If your custom provider implements HasDependencies, it can augment this graph.
Modules.override() is incredibly handy in a pinch.
Short syntax for defining parameterized keys: new Key<List<String>>() {}.
Binder.skipSources() lets you to write extensions whose error messages track line numbers properly.
The SPI. Elements.getElements() breaks a module into atoms and Elements.getModule() puts them back together.
If you implement equals() and hashCode() in a Module, you can install that module multiple times without problem.
I like how totally open the Scope interface is: basically, it's just a transformation from Provider to Provider. (Okay, from Key and Provider to Provider)
Want some things to be basically Singleton, but re-read from the database every half hour? It's easy to make a scope for that. Want to run some requests in the background, and have a scope that means "all background requests started from the same HTTP request?" It's relatively easy to write that Scope too.
Want to scope some Key on your server during tests so that it uses a separate instance for each test that you're running from a client? (With the test passing the test id in a Cookie or extra HTTP parameter) That's harder to do, but it's perfectly possible and so someone's already written that for you.
Yes, excessive abuse of Scope will cause Jesse to start hunting around for the stakes and garlic cloves, but its amazing flexibility can be really useful.
One great feature of Guice is how easy it makes implementing method interceptors in any Module, using:
public void bindInterceptor(
Matcher<? super Class<?>> classMatcher,
Matcher<? super Method> methodMatcher,
MethodInterceptor... interceptors);
Now, any method matching methodMatcher within a class matching classMatcher in that Module's scope is intercepted by interceptors.
For example:
bindInterceptor(
Matchers.any(),
Matchers.annotatedWith(Retryable.class),
new RetryableInterceptor());
Now, we can simply annotate any method with #Retryable and our RetryableInterceptor can
retry it if it fails.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have one repository that internally (on some methods) will need to use another repository.
I am trying to put all dependencies on the constructor, passing interfaces as arguments. However I don't know how to deal with this specific scenario.
Should I pass also this repository as an argument? Even though I will not use it on every method inside?
Thanks
You don't have any problem for making a repository depend on another repository. And, yes, pass it as a parameter
I'm assuming you're making dependency injection, specifically constructor injection.
Instancing an extra repository, which some times won't be used (because not all method use it) it's not such a terrible overhead that makes you to avoid it. If it was a more expensive resource (like opening a file or DB connection) you could use some alternative technique. For example expose the second repository in a property with a backing field which is populated in the first call to the property getter using service location, i.e. finding it directly in your container, or an smarter solution, provided but some of the DI frameworks, which does this kind of thing automatically, like Unity's Lazy and similar solutions.
But I insist, in this case, the overhead doesn't justify it.
NOTE: you could also use the property or Lazy technique if you had a dependency loop (circular dependency), to break the loop and make it work. However, int this case, it's much better to refactor your classes, (extracting a thrid class) to avoid the circular references. This is not your case.
I would probably make a service layer on top of the repositories. Inject both repositories into the service layer.
public LibraryCatalogueService {
IBookRepository _books;
IAuthorsRepository _authors;
public LibraryCatalogueService (IBookRepository books, IAuthorRepository authors)
{
_books = books;
_authors = authors;
}
public List<BookWithAuthor> GetBooksWithAuthors()
{
//do stuff to get books and get authors and then join them.
//return the list
}
}
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am new to Dependency Injection, using C#, so please forgive me for my lame question. I wanted to post this question anyway before investing time and buying expensive books on this subject.
After going through a few online documents, it appears that using dependency containers along with configuration files one can use this to swith from one type of implementation to another. However this could be easily done by an if/else statement and some config settings.
What is the advantage of using such a cumbersome implementation just to change from one class to another? I see abstract and factory patterns to be much more useful. Maybe I am wrong.
I ha s a real worl case where i needed dependency injection :
2 assembly : 1 responsible for computing a price when you do a search (lets call it Search), and the second responsible for computing a booking price with all the options (let's call it Booking).
The Booking assembly is already referencing Search(because it needs to know the initial price for computing the full price).
But here is the requirement : we need the price from Search to include all mandatories options (yes in the tourism industry you have mandatories options) like "full room cleaning".
So I couldn't had a ref to Booking in Search (because of circular reference). So I decided use dependency injection.
My Search assembly defined an interface
public interface IAddMandatoryOptionService{
void ChangeResultsWithMandatoryOptions(SearchResult[] results);
}
And then my Booking Assembly could implement this interface.
public class AddMandatoryOptionService : IAddMandatoryOptionService{
public void ChangeResultsWithMandatoryOptions(SearchResult[] results){
...
}
}
My SearchService class now would look like
public class SearchService{
public SearchService(IAddMandatoryOptionService optionService){
this.OptionService = optionService;
}
public SearchResult[] Search(Filter filter){
...
this.OptionService.ChangeResultsWithMandatoryOptions(results);
...
return results;
}
}
So my Search Service has no dependency to the AddMandatoryOptionService class (and the Booking assembly), but it's using its functionality.The good IAddMandatoryOptionService will be injected when I create my service (in my Application_Start or with a DI Framework)
The advantages are :
Resolving the circular reference problem.
If I want to unit test my SearchService I'll juste have to mock/fake IAddMandatoryOptionService.
Here the need for injection was more technical than logical, but I think this kind of real world scenario could help you to get the point.
In short, dependency injection is used to be able to losely couple classes. By using an if else statement you introduce a dependency between classes. When adding à new implementation to your if else statement you need to add another else statement.
You've probably read http://en.m.wikipedia.org/wiki/Dependency_injection since they have a pretty good motivation section.
Perhaps complete your q with different code examples.
For instance I have this bit of code
public class ProductService{
private IProductDataSource _dataSource = DependencyManager.Get<IProductDataSource>();
public Product Get(int id){
return _dataSource.Select(id);
}
}
I have 2 different data source:
XML file which contains the informations only in 1 language,
a SQL data base which contains the informations in many languages.
So I created 2 implementation for IProductDataSource, for for each kind of datasource.
But how do I send the required language to the SQL data source ?
I add the parameter "language" to the method "IProductDataSource.Select" even if I won't use it in the case of the XML implementation.
Inside the SQL implementation I get the language from a global state ?
I add the language to the constructor of my SQL implementation, but then I won't use my DependencyManager and handle my self the dependency injection.
Maybe my first solution is not good.
The third option is the way to go. Inject the language configuration to your SQL implementation. Also get rid of your DependencyManager ServiceLocator and use constructor injection instead.
If your application needs to work with multiple languages in a single instance I think point one is a sensible approach. If the underlying data does not provide translations for a request language then return null. There is another solution in this scenario. I'm assuming that what you have is a list of products and language translations for each product. Can you refactor your model so that you do not need to specify or asertain the langauge until you reference language specific text? The point being a product is a product regardless of the language you choose to describe it. i.e. one product instance per product, only the product id on the Datasource.Select(..) method and some other abstraction mechanism to deal with accessing the correct text translation.
If however each instance of your application is only concerned with one language set I second Mr Gloor.
First of all I need to point out that you are NOT injecting any dependencies with your example - you are depending on a service locator (DependencyManager) to get them for you. Dependency injection, simply put, is when your classes are unaware of who provides the dependencies, e.g. using a constructor, a setter, a method. As it was already mentioned in the other answers, Service locator is an anti-pattern and should be avoided. The reasons are described in this great article.
Another thing is that the settings you are mentioning, such as language or currency, seem to be localization related and would probably be better dealt with using the built-in mechanisms of your language of choice (e.g. resource files, etc).
Now, having said that, depending on how the rest of your code is structured you have several options to solve this while still using Service locator:
You could have SqlDataSource depend on some ILanguageProvider which pulls the current language from somewhere. However, with more settings like these (or if it is difficult to get current language in an isolated way) this can get messy very fast.
You could depend on IProductDataSourceFactory instead (or, if you are using C#, Func<IProductDataSource>) which would return the concrete implementation with the correct settings. Again, you need to be able to get the current language in an isolated way in order to use this.
You could go with option 1 in your question. This would be a leaky abstraction but would be the simplest to implement.
However, if you decide to get rid of service locator and start using some DI container, the best solution would be using option 3 (as it was already stated) and configuring container accordingly to provide the correct value. Some good ideas of how to do this in an elegant way can be found in the answer to this question
Something that has been bugging me since I read an answer on another stackoverflow question (the precise one eludes me now) where a user stated something like "If you're calling the Service Locator, you're doing it wrong."
It was someone with a high reputation (in the hundred thousands, I think) so I tend to think this person might know what they're talking about. I've been using DI for my projects since I first started learning about it and how well it relates to Unit Testing and what not. It's something I'm fairly comfortable with now and I think I know what I'm doing.
However, there are a lot of places where I've been using the Service Locator to resolve dependencies in my project. Once prime example comes from my ModelBinder implementations.
Example of a typical model binder.
public class FileModelBinder : IModelBinder {
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
ValueProviderResult value = bindingContext.ValueProvider.GetValue("id");
IDataContext db = Services.Current.GetService<IDataContext>();
return db.Files.SingleOrDefault(i => i.Id == id.AttemptedValue);
}
}
not a real implementation - just a quick example
Since the ModelBinder implementation requires a new instance when a Binder is first requested, it's impossible to use Dependency Injection on the constructor for this particular implementation.
It's this way in a lot of my classes. Another example is that of a Cache Expiration process that runs a method whenever a cache object expires in my website. I run a bunch of database calls and what not. There too I'm using a Service Locator to get the required dependency.
Another issue I had recently (that I posted a question on here about) was that all my controllers required an instance of IDataContext which I used DI for - but one action method required a different instance of IDataContext. Luckily Ninject came to the rescue with a named dependency. However, this felt like a kludge and not a real solution.
I thought I, at least, understood the concept of Separation of Concerns reasonably well but there seems to be something fundamentally wrong with how I understand Dependency Injection and the Service Locator Pattern - and I don't know what that is.
The way I currently understand it - and this could be wrong as well - is that, at least in MVC, the ControllerFactory looks for a Constructor for a Controller and calls the Service Locator itself to get the required dependencies and then passes them in. However, I can understand that not all classes and what not have a Factory to create them. So it seems to me that some Service Locator pattern is acceptable...but...
When is it not acceptable?
What sort of pattern should I be on the look out for when I should rethink how I'm using the Service Locator Pattern?
Is my ModelBinder implementation wrong? If so, what do I need to learn to fix it?
In another question along the lines of this one user Mark Seemann recommended an Abstract Factory - How does this relate?
I guess that's it - I can't really think of any other question to help my understanding but any extra information is greatly appreciated.
I understand that DI might not be the answer to everything and I might be going overboard in how I implement it, however, it seems to work the way I expect it to with Unit Testing and what not.
I'm not looking for code to fix my example implementation - I'm looking to learn, looking for an explanation to fix my flawed understanding.
I wish stackoverflow.com had the ability to save draft questions. I also hope whoever answers this question gets the appropriate amount of reputation for answering this question as I think I'm asking for a lot. Thanks, in advance.
Consider the following:
public class MyClass
{
IMyInterface _myInterface;
IMyOtherInterface _myOtherInterface;
public MyClass(IMyInterface myInterface, IMyOtherInterface myOtherInterface)
{
// Foo
_myInterface = myInterface;
_myOtherInterface = myOtherInterface;
}
}
With this design I am able to express the dependency requirements for my type. The type itself isn't responsible for knowing how to instantiate any of the dependencies, they are given to it (injected) by whatever resolving mechanism is used [typically an IoC container]. Whereas:
public class MyClass
{
IMyInterface _myInterface;
IMyOtherInterface _myOtherInterface;
public MyClass()
{
// Bar
_myInterface = ServiceLocator.Resolve<IMyInterface>();
_myOtherInterface = ServiceLocator.Resolve<IMyOtherInterface>();
}
}
Our class is now dependent on creating the specfic instances, but via delegation to a service locator. In this sense, Service Location can be considered an anti-pattern because you're not exposing dependencies, but you are allowing problems which can be caught through compilation to bubble up into runtime. (A good read is here). You hiding complexities.
The choice between one or the other really depends on what your building on top of and the services it provides. Typically if you are building an application from scratch, I would choose DI all the time. It improves maintainability, promotes modularity and makes testing types a whole lot easier. But, taking ASP.NET MVC3 as an example, you could easily implement SL as its baked into the design.
You can always go for a composite design where you could use IoC/DI with SL, much like using the Common Services Locator. You component parts could be wired up through DI, but exposed through SL. You could even throw composition into the mix and use something like the Managed Extensibility Framework (which itself supports DI, but can also be wired to other IoC containers or service locators). It's a big design choice to make, generally my recommendation would be for IoC/DI where possible.
Your specific design I wouldn't say is wrong. In this instance, your code is not responsible for creating an instance of the model binder itself, that's up to the framework so you have no control over that but your use of the service locator could probably be easily changed to access an IoC container. But the action of calling resolve on the IoC container...would you not consider that service location?
With an abstract factory pattern the factory is specialised at creating specific types. You don't register types for resolution, you essentially register an abstract factory and that builds any types that you may require. With a Service Locator it is designed to locate services and return those instances. Similar from an convention point of view, but very different in behaviour.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In ASP.NET MVC, the ActionResult class, which is the base for all results returned by action methods from a controller, is defined as an abstract class with the single method (© Microsoft):
public abstract void ExecuteResult(ControllerContext context);
Can you think of any specific reasons for this design? Specifically, it seems a bit weird to me, that
there is no IActionResult interface,
and that the class would not be required at all, if there was such an interface.
After all, if this was an interface instead of that abstract class, there would be no need to extend a base class in order to create a new ActionResult - one would just have to implement IActionResult properly. In a world, err language, without multiple inheritance, this advantage would seem quite important to me.
Interfaces are great for allowing a class to implement multiple contracts, such as when you know that a type must be two different things. In some cases, this can encourage creating a type that has too many responsibilities.
Action results have a single responsibility and it didn't seem like there would be any scenario where you need an object to be both an action result and something else. Even if you did, it's possible to do via composition. So in this case, we went with ABS to allow us greater flexibility after we RTM to make changes if necessary.
However, if there's a specific scenario we're blocking in which an interface would be preferable, we'll consider it. We can always do it later in a manner that's not breaking.
You can even do it yourself by writing your own action invoker, which only requires you to implement IActionInvoker (an interface) and that invoker could check for your own IActionResult rather than ActionResult.
I'm gonna guess because they were anticipating the ActionResult to gain methods and properties over the life of the CTP/beta. If it was an interface, every change to IActionResult would break existing code. Adding another method to the abstract base class wouldn't cause any problems.
You implement interfaces and you inherit from abstract classes.
For me it is the difference between "being of a type" or "acting like a type"
Since C# doesn't support multiple inheritance you are forced to define your class as an ActionResult, instead of something that acts as an ActionResult.
Compare it to the class EventArgs. Why does it make sense to inherit EventArgs instead of a IEventArgs interface. Well because an EventHandler carries something around of type EventArgs, not something acting as an EventArgs class.
I know this isn't exactly what you are looking for but for hahas I opened up the MVC3 source, changed ActionResult to IActionResult, ran a couple of find and replaces and everything built fine.
This means to me that ActionResult is an abstract class for an API reason. Maybe its as simple as the MVC team wanted you to be able to use Fields or didn't want to give people the ability to do crazy IActionResult, ISomething, IMyNuttyThing.
A scenario that I would think IActionResult would help is for dependency injection. I would like to have one set of controllers that are shared between a SPA and a razor UI. In configuration I would like to dynamically set the application type and have my controllers
public ActionResult Get(){
var customer = new Customer();
return View(customer);
}
I would like the concrete View method to be determined at runtime based on the application type. ie. Json() or ViewResult()
The object I pass into the result for both cases is going to be the same.
Does that make sense? Or is this possible without an IActionResult?