I have run into a scenario that I would like to solve with Ninject but up until this point none of my work with it has cross this type of situation.
WCF Service App
W3C Log Parsing App (overly simplistic for demonstration purposes).
IW3CLogItem implemented by W3CLogItem
W3CLogItem has a public member of type IUrlData (contains the important data but can be one of 5 concrete implementations depending on what it contains).
The decision of which concrete implementation to use is based off of a string match and its constructor takes a regex pattern it will use to parse the data as well as the string to be parsed.
Currently I have a simple factory that does the string comparisons and then calls Create() to return a new concrete object (DocumentUrlItem, DriverUrlItem, AssetUrlItem, etc...).
I was looking at the wiki docs and how to name a binding, but even that only gets me half of the way.
The question I have is: Can this be done without a factory? Can I somehow place a conditional attribute on a binding (i.e. .contains, etc...) that evaluates to true to know which binding to use or am I better off sticking with the factory?
Let elaborate a bit.
If I were to write the factory without ninject in a simplified way, it would look like this:
protected IUrlData Create(string urldata)
{
if (urldata.Contains("bob"))
{
return new BobUrlData(urldata)
}
else if (urldata.Contains("tim"))
{
return new TimUrlData(urldata);
}
}
A couple of things of note:
1) The number of classes that implement IUrlData will grow over time. The strings "tim", and "bob" will be coming from a database.
2) The urldata being passed into BobUrlData and TimUrlData is not the only parameter in the real world, there will also be a regular expression (also sourced from the database which is calculated by the entries timestamp that knows how to handle that particular entry as they have evolved over time.
3) I am really curious if this can be accomplished with Ninject without the need for the factory all together, to somehow through metadata or names achieve the same work but all through bindings all while leaving the code extensible but read-only (other than the binding modules).
You are able to bind to methods with Ninject.
Ninject Wiki - Contextual Binding
You shouldn't need the factory anymore if you set up the method to return what you need. I can't say one is better than the other though since they both work, but I do prefer the factory doing the work and having that access Ninject to give me the correct implementation. Your result is still the same in the end.
Also, right above on the same page is Specifying Constraints.
from a purist point of view, an abstract factory is the correct way to abstract out the implementation from the interface of an object. with that said, ninject offers various ways of implementing what you want without using an abstract factory. The ones that I feel will help you most are ToMethod and providers
Related
This question may well have been asked before but I didn't find anything whilst searching SO.
When using Dependency Injection, how do you normally handle types such as lists, network credentials etc.
At the moment in one of my services constructors I have:
_itemsCheckedForRelations = new List<Guid>();
_reportManagementService.Credentials = new NetworkCredential([...]);
Would you refactor these out into a custom factory class/interface and inject them or do as I've done here?
I'm never quite sure how to handle these types of object creation.
You can easily replace List<Guid> with IList<Guid> or ICollection<Guid> - or even IEnumerable<Guid> if you only need to read the list.
For other BCL types that don't already implement an interface or have virtual members, you'll need to extract an interface yourself. However, when doing that, you should watch out for Leaky Abstractions.
You can two routes; Firstly, as you say, create a wrapper for them and inject this. However this depends on how you want populate the state of the objects you're wrapping. This case that's not something I'd personally do. Check out Krzysztof Kozmic blog about dynamic parmaters:
Castle Windsor dynamic parameters
Hope this helps
I am developing a kind a translator from language A to B (yeah, it kinda is like a compiler). A translation is generally from several different files and each one of them has the same 3 sections to translate. So, the way I did it, I kind of have it the following way:
When I instantiate a translator and give it some data, it will need to generate all the needed FileTranslator classes. As I shouldn't do the new in Translator, I should ask for a factory from above. The same happens in the Sections translators. This poses the problem that I'm forced to create a lot of boilerplate factories. Moreover, each one of the translators might need even more factories to generate some other classes they might want to use.
Am I thinking this the wrong way or is it just the way it is? I am not allowed to use any kind of DI/IoC framework in this project, btw.
Edit:
I'm afraid I am not getting my message get sent across.
In this specific case, as my Translator class needs to be able to generate at any moment some FileTranslator, it would need a FileTranslatorFactory. I know I can have an IoC Container do the wiring for me, but the IoC Container in itself will not save me for the problem of having to code up the code of the FileTranslatorFactory itself. Am I right?
Now, the problem is that a FileTranslator will also have to be able to generate whenever it needs SectionATranslators, SectionBTranslators and SectionCTranslators (and do not think they are any similar because their names are -- they are totally different and have nothing to do with each other!). So I'd have to define factories for each one of them. So for such a simple 5 classes system, I'd need to create 4 (!!!) factories.
Being that I don't want my domain objects to depend on an IoC-Container and that I don't want to have a single factory for all the 4 kinds of objects that seem to need one, am I still missing something?
The fact that there is a lot of boilerplate code involved in handcranking DI for class hierarchies like this is WHY the frameworks exist. Sorry, but unless you can get whoever decided on the no DI/IoC frameworks rule to change their mind, you are either going to be writing lots of boilerplate code, or you will end up writing a framework yourself.
EDIT - with a completely fictitious framework, to keep this as agnostic as possible, but explaining how you can eliminate all but one call into the container in many scenarios.
So, with an implementation of Translator like:
public class Translator
{
private ITranslator translatorInstance;
public Translator()
{
SomeContainer container = SomeContainer.CreateFromConfig(configFilePath);
// this is the ONLY point we touch the container
translatorInstance = container.GetMeA<ITranslator>();
}
// implementation
}
We can see that this works as a factory, and is the only class that needs to know about the container itself. An implementation of one concrete implementor of ITranslator could therefore be:
public class FileTranslator : ITranslator
{
// private fields
public FileTranslator( ISectionATranslator sectionAtrans,
ISectionBTranslator sectionBtrans,
ISectionCTranslator sectionCtrans)
{
this.sectionAtrans = sectionAtrans;
// etc
}
// implementation
}
Note here that FileTranslator knows nothing about which concrete classes actually implement the interfaces it depends on, nor does it need any sort of factory. In fact, the container will do this for you. There are several ways containers work this stuff out, one example is explicit config, something like:
<!-- absolutely fictitious configuration file, but similar to many frameworks -->
<ContainerConfig>
<ObjectResolver interface="ITranslator">
<ConcreteType type="FileTranslator">
<ConstructorInjection>
<Argument ordinal="0" type="SectionATranslator" />
<Argument ordinal="1" type="SectionBTranslator" />
<Argument ordinal="2" type="SectionCTranslator" />
</ConstructorInjection>
</ConcreteType>
</ObjectResolver>
</ContainerConfig>
Many frameworks don't even need you to define the specific constructor arguments, you can just state that if you want a ISectionATranslator then return a SectionATranslator and it will automatically create these before calling the constructor.
Also note that some frameworks provide the option to define these type resolution rules in code, using fluent style APIs, and some allow you to define multiple potential ways of resolving a particular type, via some name (perhaps a "Production" implementation versus a "UnitTest" implementation).
Note that I have kept the above deliberately vague because I don't want to say which framework is best (and to be honest, I think it depends on your individual needs) - check elsewhere on StackOverflow for framework comparisons, and please try a few out (perhaps you can try some without telling your boss!). Hopefully, however, the above shows why an IoC container can make your code much cleaner by removing the need for layers upon layers of factory classes.
I have to design a data validation framework, which basically breaks down in these components.
Data Accessors - what's the best way
to deal with this
Object Builders -
how should I prepare for future
object structures
Validators (Strategy Pattern)
I have to apply some rules on data, but I don't know what that data set would be like in future.
So I am confused after a lot of thinking whether Rules should know about how the object looks like or is it possible without Rule and data being dependent (I have a feel that, yes it is but don't know how). I am finding it hard to design abstraction for dataset.
any clues, in what direction I should think?
language - C# (.NET)
platform - Windows
EDIT: exact question
in Stratagy pattern, is it possible that Context can hold generic object and strategy can deal with that, without knowing how the object is constructed ?
In a validation framework, you usually have a set of "out-of-the-box" rules that don't know anything about what the object/entity looks like. For example, you might have a NotNullRule to check a given property is not null:
//code is not REAL code!
var user = new User({username=null, email="hello#test.com");
var notNullrule = new NotNullRule( typeof(User).GetProperty("username"), user );
var errors = notNullrule.Check();
Debug.Assert( errors[0] == "Property Username cannot be null");
It's common to use attributes to setup which validation strategy to use on which properties of a class. See this example here.
Validation frameworks usually let you create custom rules too, that might be domain specific. For example:
public class CustomerIsEligibleForDiscount : Rule
{
public void Check(){ ... }
}
Hope this helps.
If you define an abstract/base class that calls an abstract ValidateRules() method when necessary, then you can implement ValidateRules() within each class that inherits from the abstract/base class.
Declaring the method as abstract in the base class enforces its implementation in any derived class.
Is there any reason you can't use one of the many existing C# Validation Frameworks as a starting point? They tend to have conventions built in for handling these concerns.
http://validationframework.codeplex.com/
http://xval.codeplex.com/
http://msdn.microsoft.com/en-us/library/aa480193.aspx
http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs
When I create classes, simple constructors tend to be the norm. On one of my current projects, a movie library, I have a Movie domain object. It has a number of properties, resulting in a constructor as follows:
public Movie(string title, int year, Genre genre, int length, IEnumerable<string> actors)
{
_title = title;
_year = year;
_genre = genre;
_length = length;
_actors = new List<string>(actors);
}
This isn't terrible, but it's not simple either. Would it be worthwhile to use a factory method (static Movie CreateMovie(...)), or a perhaps an object builder? Is there any typical pattern for instantiating domain classes?
UPDATE: thanks for the responses. I was probably overthinking the matter initially, though I've learned a few things that will be useful in more complex situations. My solution now is to have the title as the only required parameter, and the rest as named/optional parameters. This seems the all round ideal way to construct this domain object.
If you are using .NET 4.0, you can use optional/named parameters to simplify the creation of an object that accepts multiple arguments, some of which are optional. This is helpful when you want to avoid many different overloads to supply the necessary information about the object.
If you're not on .NET 4, you may want to use the Object Builder pattern to assembly your type. Object builder takes a bit of effort to implement, and keep in sync with you type - so whether there's enough value in doing so depends on your situation.
I find the builder pattern to be most effective when assembling hierarchies, rather than a type with a bunch of properties. In the latter case, I generally either overloads or optional/named parameters.
Yes, using a factory method is a typical pattern, but the question is: Why do you need it? This is what Wikipedia says about Factory Methods:
Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.
So, the factory method pattern would make sense if you want to return subclasses of Movie. If this isn't (and won't be) a requirement, replacing the public constructor with a factory method doesn't really serve any purpose.
For the requirements stated in your question, your solution looks really fine to me: All mandatory fields are passed as parameters to the constructor. If none of your fields are mandatory, you might want to add a default initializer and use the C# object initializer syntax.
It depends.
If that is the only constructor for that class, it means all the properties are required in order to instantiate the object. If that aligns with your business rules, great. If not, it might be a little cumbersome. If, for example, you wanted to seed your system with Movies but didn't always have the Actors, you could find yourself in a pickle.
The CreateMovie() method you mention is another option, in case you have a need to separate the internal constructor from the act of creating a Movie instance.
You have many options available to your for arranging constructors. Use the ones that allow you to design your system with no smells and lots of principles (DRY, YAGNI, SRP.)
I don't see anything wrong with your constructor's interface and don't see what a static method will get you. I will have the exact same parameters, right?
The parameters don't seem optional, so there isn't a way to provide an overload with fewer or
use optional parameters.
From the point-of-view of the caller, it looks something like this:
Movie m = new Movie("Inception", 2010, Genre.Drama, 150, actors);
The purpose of a factory is to provide you a customizable concrete instance of an interface, not just call the constructor for you. The idea is that the exact class is not hard-coded at the point of construction. Is this really better?
Movie m = Movie.Create("Inception", 2010, Genre.Drama, 150, actors);
It seems pretty much the same to me. The only thing better is if Create() returned other concrete classes than Movie.
One thing to think about is how to improve this so that calling code is easy to understand. The most obvious problem to me is that it isn't obvious what the 150 means without looking at the code for Movie. There are a few ways to improve that if you wanted to:
Use a type for movie length and construct that type inline new MovieLength(150)
Use named parameters if you are using .NET 4.0
(see #Heinzi's answer) use Object Initializers
Use a fluent interface
With a fluent interface, your call would look like
Movie m = new Movie("Inception").
MadeIn(2010).
InGenre(Genre.Drama).
WithRuntimeLength(150).
WithActors(actors);
Frankly, all of this seems like overkill for your case. Named parameters are reasonable if you are using .NET 4.0, because they aren't that much more code and would improve the code at the caller.
You gave a good answer to your own question, it's the factory pattern. With the factory pattern you don't need huge constructors for encapsulation, you can set the object's members in your factory function and return that object.
This is perfectly acceptable, IMHO. I know static methods are sometimes frowned upon, but I typically drop that code into a static method that returns an instance of the class. I typically only do that for objects that are permitted to have null values.
If the values of the object can't be null, add them as parameters to the constructor so you don't get any invalid objects floating around.
I see nothing wrong with leaving the public constructor the way it is. Here are some of the rules I tend follow when deciding whether to go with a factory method.
Do use a factory method when initialization requires a complex algorithm.
Do use a factory method when initialization requires an IO bound operation.
Do use a factory method when initialization may throw an exception that cannot be guarded against at development time.
Do use a factory method when extra verbage may be warranted to enhance the readability.
So based on my own personal rules I would leave the constructor the way it is.
If you can distinguish core data members from configuration parameters, make a constructor that takes all of the core data members and nothing else (not even configuration parameters with default values—shoot for readability). Initialize the configuration parameters to sane default values (in the body of the method) and provide setters. At that point, a factory method could buy you something, if there are common configurations of your object that you want.
Better yet, if you find you have an object that takes a huge list of parameters, the object may be too fat. You have smelled the fact that your code may need to be refactored. Consider decomposing your object. The good literature on OO strongly argues for small objects (e.g. Martin Fowler, Refactoring; Bob Martin, Clean Code). Fowler explain how to decompose large objects. For example, the configuration parameters (if any) may indicate the need for more polymorphism, especially if they are booleans or enumerations (refactoring "Convert Conditional to Polymorphism").
I would need to see the way that your object is used before giving more specific advice. Fowler says that variables that are used together should be made into their own object. So, sake of illustration, if you are calculating certain things on the basis of the genre, year and length, but not the other attributes, those together may need to be broken out in to their own object—reducing the number of parameters that must be passed to your constructor.
As for me - all depending on your domain model. If your domain model allows you to create simple objects - you should do it.
But often we have a lot of composite objects and the creation of each individually is too complicated. That's why we`re looking for the best way to encapsulate the logic of composite object creation. Actually, we have only two alternatives described above - "Factory Method" and "Object Builder". Creating object through the static method looks a bit strange because we placing the object creation logic into the object. Object Builder, in turn, looks to complicated.
I think that the answer lies in the unit tests. This is exactly the case when TDD would be quite useful - we make our domain model step-by-step and understand the need of domain model complexity.
I'm working on a module that requires a strictly decoupled interface. Specifically, after instantiating the root object (a datasource), the user's only supposed to interact with the object model via interfaces. I have actual factory objects (I'm calling them providers) to supply instances that implement these interfaces, but that left the clumsiness of getting the providers. To do so, I've supplied a couple methods on the datasource:
public class MyDataSource
{
private Dictionary<Type, Type> providerInterfaceMapping = new Dictionary<Type, Type>()
{
{ typeof(IFooProvider), typeof(FooProvider) },
{ typeof(IBarProvider), typeof(BarProvider) },
// And so forth
};
public TProviderInterface GetProvider<TProviderInterface>()
{
try
{
Type impl = providerInterfaceMapping[typeof(TProviderInterface)];
var inst = Activator.CreateInstance(impl);
return (TProviderInterface)inst;
}
catch(KeyNotFoundException ex)
{
throw new NotSupportedException("The requested interface could not be provided.", ex);
}
}
}
I've modified some details on the fly to simplify (e.g., this code snippet doesn't include the parameters passed to the implementation instance that's created). Is this a good general approach for implementation of a factory method in C#?
You should rather take a step back and ask whether using a factory method at all is a good idea? In my opinion, it is not.
There are more than one issue with factory methods, and your example illustrates several:
You need to have a hard reference to the implementation (FooProvider in addition to IFooProvider), which is exactly the situation you are trying to avoid in the first place. Even if the rest of your code only consumes IFooProvider, your library is still tightly coupled to FooProvider. Some other developer may come by and start using FooProvider directly if he/she isn't aware of your factory method.
You only support implementations that have default constructors, since you are using Activator.CreateInstance. This prevents you from using nested dependencies.
Instead of trying to manually control dependencies, I would recommend that you take a look at Dependency Injection (DI). Whenever your code needs an IFooProvider, supply it with Constructor Injection.
Don't reinvent your own implementation of dependency injection, use an existing library like Spring.NET or the Microsoft Unity application block.
Injecting dependencies is a common programming problem that you shouldn't have to solve yourself. There are some nice lightweight libraries out there (I mentioned a couple above) that do the job well. They support both declarative and imperative models of defining dependencies and are quite good at what they do.
Technically this is fine, however most times when I see a factory it usually returns the same type interface, for instance something like IProvider rather than IFooProvider or IBarProvider which to me doesn't make sense. If you are going to have FooProvider and BarProvider then why have different interfaces for them. I would use one interface IProvider and have FooProvider and BarProvider implement that.
Regardless of the rightness or wrongness of using the factory method (as that is not what you asked about!), your implementation looks fine to me.
Something that may work for you better than hardcoding the type mapping is putting that info in a configuration file and loading it in your app.
For what it is worth I use this pattern all the time and have abstracted some of this sort of logic into a reusable assembly. It uses reflection, generics and attributes to locate and bind the concrete types at runtime. http://www.codeproject.com/KB/architecture/RuntimeTypeLoader.aspx
This helps to address Mark's concern because implementation types are not hardcoded, and further the implementation types are determined by the installation, not in project assembly references.