Is this a good factory method implementation? - c#

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.

Related

Ninject (IoC) and an alternative to a factory with conditional logic

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

Dependency Injection for built in types

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

Dependency Injection in projects that have lots of classes that need to generate on the fly other classes

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.

Can I take advantage of Dependency Injection here?

I'm working on a project that's using the MS Application Blocks. I see the 'Unity' dll is available to me. It's version 1.1 by the way. How can I use dependency injection here?
I have a class
public class ScheduleDataDetailsDC
{
public int ScheduleID;
public List<ScheduleRateLineItem> MinRateList;
public List<ScheduleRateLineItem> MaxRateList;
public List<ScheduleRateLineItem> VotRateList;
public List<ScheduleLOSRateDC> LosRateList;
public List<ScheduleRateParamsDC> RateParams;
}
So when I new it up I am doing this...
new ScheduleDataDetailsDC{
LosRateList = new List<ScheduleLOSRateDC>()
, MaxRateList = new List<ScheduleRateLineItemDC>()
, MinRateList = new List<ScheduleRateLineItemDC>()
, RateParams = new List<ScheduleRateParamsDC>()
, VotRateList = new List<ScheduleRateLineItemDC>()
}
Can Unity 1.1 Help me in anyway here? I would like to just be able to use var x = new ScheduleDetailsDC(), and those 5 inner lists be initialized for me. Can Unity do anything for me here? Please note I've never used DI before.
Thanks for any pointers,
~ck in San Diego
The best thing to do would be to initialise the lists in the constructor and deny direct access to them from other classes by making them into properties:
public class ScheduleDataDetailsDC
{
public ScheduleDataDetailsDC()
{
this.MinRateList = new List<ScheduleRateLineItem>();
//inialise other lists
}
public List<ScheduleRateLineItem> MinRateList { get; private set; }
...
}
It doesn't seem as though dependency injection can really be of use here since the class seems to be a simple data container, although it's difficult to tell without more context.
Yes Unity can help you, but I think it's not the case. You can just initialize your lists incide your object giving them default instances, Unity as any other IoC container shouldn't be used as a simple object builder (despite it could).
I'm not sure specifically what the details of the 1.1 release of Unity are, but generally speaking whenever you are using an Inversion of Control Container, you have to go through the following steps:
Register the types your IoC container (Unity in your case) knows about. This includes all of the main types that you plan to request, plus all of the dependent types. In your case you will need to let it know about ScheduleDataDetailsDC, and what, exactly needs to go into each of the lists that are considered dependencies
Your types should specify all of the required dependencies as constructor arguments. This is what the IoC Container will look at to determine what needs to be injected. If you have optional dependencies then you can use Property Injection to support that (if your IoC container supports it, which I think Unity does)
You must request an instance of your registered type from the container. How exactly you do this depends on you container. There should be a method like Get<T>() or Resolve<T>. Generally your going to request instances of the "Highest Level" classes, i.e the ones that are used somewhere near the entry point for your software. If you do this, and you have applied Dependency Injection for all dependent classes down the line (and you've correctly registered all of the dependent types) you should get an object with all of it's dependencies supplied, and likewise all of that objects dependencies should be supplied, and on down the line.
You also tend to see Interfaces used in conjunction with IoC a lot since you can bind a concrete type to the interface type, and then specify that interface as your dependency. This allows you to apply business rules and configuration values during the binding process that will give you the ability to use different concrete implementations in cases where you would need to do such a thing.
So given all of this, it's hard to say exactly what would be involved in utilizing Unity in the situation you've outlined above. Firstly you would need to register ScheduleDataDetailsDC, but to get the dependencies in place you would also need to register each of the List types, or more specifically each concrete object that would go in each list (and then, of course all of the dependencies for those classes). Since I'm not really sure what the roles of those lists are, it's hard for me to say how you could go about doing that (or even if you could go about doing that).

Linq2Sql, OOP, DependencyInjection problem

I'm still struggling a bit with OOP concepts and dependency injection so bear with me.
I have generated my Linq2Sql model with a User table and now I would like to be able to send a confirmation email to this user so I created a partial class file for my User object and I felt it was natural to add a SendConfirmationEmail() method to the User class. This method will use a MailService to send the actual email and I would like to use dependency injection to pass in the service so I created a constructor overload on the User object like this
public User(IMailService service) : this()
{
_service = service;
}
The SendConfirmationEmail method would look like this
public void SendConfirmationEmail()
{
_service.SendMail(params...);
}
I realize this is a kind of poor mans dependency injection and I hope to switch to a dependency injection framework later as I am getting more grips on this.
The problem for me is that I need to make a reference from my model dll to my service dll which does not seem right and because I am unsure of how nice my linq2sql generated entities plays with Dependency injection frameworks and OOP concepts (I think ninject looks most promising).
I was hoping someone with a bit more experience than me could tell I'm if I am going in the right direction with this. I know I can make it work but I would like to educate my self in doing it in the correct way in the same step.
I personally would change some things in your architecture:
I don't think that SendConfirmationEmail should be a method on your User object. But should be a method on another object with the user as a parameter. (this also better seperates your Dal from the other logic.
Second in this method use something like this:
Services.Get<IMailService>().SendMail(params ...);
You can implement Services as the folowin (just an example):
public class Services
{
protected static Dictionary<Type, object> services = new Dictionary<Type, object>();
private Services()
{
}
static Services()
{
// hard coded implementations...
services.Add(typeof(IMailService), new DefaultMailServiceImplementation());
}
public static T Get<T>() where T : class
{
Type requestedType = typeof(T);
return services[requestedType] as T;
}
}
By using a "Services"-class (or call it what you like) you add an additional layer between the IOC-framework and your code which makes it easy to change IOC-frameworks. Just change the implementation in the Get method to use one. You can also use a hardcoded temporary solution (until you use an IOC-framework) in the static constructor (like I did in the above example).
The problem with that approach is that much of the time the entity is going to come from the LINQ-to-SQL back-end, and so isn't going to use your constructor (LINQ-to-SQL creates objects in its own way; you cannot force LINQ-to-SQL to use your constructor) - so this would only be useful for the (few) objects you create yourself. Data-binding (etc) will also commonly use the parameterless constructor by default.
I wonder if this wouldn't work better as a utility method that accepts the service, or obtains the service itself via a factory / singleton.
I think you're ok doing this, but you might want to do two additional things to protect yourself from future cross-layer dependency problems:
Create an interface for your User
object. You should do this because
not doing so will mean that
everything that consumes this
business object will have to
reference the LINQ dlls
unnecessarily.
Move your dependency injection from
the constructor into a property.
You do this because constructor
injection tends to limit your
ability to dynamically create your
object. Doing this, though poses a
problem, since you would have to
implement a lot of null checking
code for _service. You can fix this
by creating an "empty"
implementation of IMailService and
make it the default value for
_service.

Categories