Simple Factory with reflection C# - c#

Simple factory using reflection involves storing (registering) various type names with their corresponding class type in a hash table, then using this hash table for generating objects in the factory.
interface Product
{
void foo();
}
class ProductFactory
{
HashTable m_RegisteredProducts = new HashTable();
public void registerProduct(string productID, Type p) {
m_RegisteredProducts.add(productID, p);
}
public Product createProduct(string productID){
return (Product) new m_RegisteredProducts[productID];
}
}
I'm not clear on when does the process of registering a new type happen since all types to be used are to be loaded into the hash table at runtime. Where is the call to registerProduct() to be made?
Calling registerProduct() for all different classes at a single place inside ProductFactory class doesn't make sense since it would defeat the purpose of using reflection over naive switch/case method.
If registerProduct() is called inside the class definition of all classes implementing the interface, then an instance of the class is created after/using the Factory hence will always give an error.

Your code doesn't do reflection as it's expecting an instance implementing the Product interface, not a type. You would need addProduct to take a Type instance, check if it implements the Product interface, then dynamically create instances of it in createProduct (using something like type.GetConstructor(<constructor signature>).Invoke(<arguments>);)
Here's an article I wrote a long time ago on something similar: http://blixt.org/2009/06/05/getting-types-implementing-class-or-interface

Calling registerProduct() for all different classes at a single place inside ProductFactory class doesn't make sense since it would defeat the purpose of using reflection over naive switch/case method.
Reflection is useful when extended product classes are added into a location (say a plug-ins directory). You have a list of strings to identify the supported plug-ins that can either be defined in a text file (application properties, which provides an added layer of security) or by (via reflection) scanning said plug-ins directory (less secure if someone can drop a hacked product in there). Disclaimer: I've never done this in C#, but it works well in Java. Apart from new product code and eventually modifying the properties file, there is no modification to the application code.
If registerProduct() is called inside the class definition of all classes implementing the interface, then an instance [of] the class is created after/using the Factory hence will always give an error.
I'm not sure that's always the strategy of the code in your question (where is it from?). You might want to read more about the different strategies of reflection combined with simple factory at http://www.codeproject.com/Articles/37547/Exploring-Factory-Pattern

It depends. There are different scenarios that call for different strategies.
One strategy that I saw quite often if all product types are defined in the same assembly (or a list of assemblies) you could call something like this:
var productTypes= from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(IProduct));
and then call registerProduct() for every element in productTypes.

Related

When to use generic instances instead of just using "new" keyword

I've been thinking about having multiple page elements and making tabbing with a PageFactory. Then I realized it would be better to not to type all the types that I want, since I just wanna get the instance.
Then I created something as follows:
public static T GetInstance<T>() where T:IPage, new()
{
return new T();
}
But the point is, I can just create my pages like new WelcomePage(); instead of PageFactory.GetInstance<WelcomePage>() and it doesn't make sense to me to have a generic method like that. But I see it is something used before.
So, what is the benefit of using that generic way to get an instance. I'd be happy to hear, probable needs.
Given that this is static method, I see no benefits over new, except usage of GetInstance in other generic methods. (Non static factory, as a part of interface or abstracts class, and with more that 1 implementation, would get more sense, as client would not depend on specific factory, or e.g. different factory could be used in tests than in production).
I would prefer new, because:
it's immediately understandable, and doesn't require an extra looking into implementation details of GetInstance
given that GetInstance<T> is generic, and constructor constraints on generics are limited to parameterless constructor new (), this implies that dependencies will be injected into T object via properties or ambient environment, neither of which is ideal. Dependency injection via constructor is much better.

How to instruct Ninject to use a factory method for any requested subtype of a given type?

I have a base Dto type where I have several common logic and code (change notifications, validations, etc.). Due to technical reasons whenever I have to create an instance of a concrete DTO type like PersonDTO I have to use a factory method.
var personDto = Dto.Create<PersonDTO>();
// or a non-generic variant like
var personDto = Dto.Create(typeof(PersonDTO));
Now how could I ask Ninject to use this factory method whenever I need inject any Dto descendant? I mean something like
Bind<Dto>().ToMethod(ctx => Dto.Create(ctx.Request.Service));
but which could get applied to not only the base Dto requests but also to every request for any Dto descendant type.
I know I could probably use the conventions Ninject extension's "for all ..." kind of feature, but I'd rather like a way without yet another library if possible.
For every type which needs to be resolvable (IResolutionRoot.Get<SomeType>()), there needs to be a binding, for example:
Bind<Dto>().To..
Bind<DtoBla>().To..
except in case you'll do a binding with multiple types such as:
Bind<Dto,DtoBla>().To...
this overload is specifically useful when you want to bind multiple types to the same instance, for example if you want to have a singleton FooBar : IFoo, IBar resolve as IFoo and IBar.
Now in case you have to do a lot of very similar bindings, Ninject.Extensions.Conventions is just a library to make the task easier for you. You don't need to use it, you can also program type detection (using reflection) and binding creation yourself.
The reflection part has been covered many times over and over on stackoverflow, see for example:
Generating a list of child classes with reflection in .NET 3.5
Register all declared child classes of a class in C#
Get all derived types of a type
Search an assembly for all child types?
Of course, if you don't want to use Ninject.Extensions.Reflection, you can also just go look at its source code to see how it's done and copy the relevant parts! ;-)

How to configure the factory to generate the object?

Maybe the title is not so clear. Let me clarify what I'm trying to accomplish.
I have to base classes:
BaseProperties
BaseProblem
BaseProperties contains data about the generation of math problems. For example, in the image above, BasicAdditionProperties contains Addend1 and Addend2, this two objects know about the range of the generated value to represent a BasicAdditionProblem.
So, this is just an idea.. I guess I supposed to pass the abstract class to a factory, and this one should generate the problem (in this case BasicAdditionProblem).
I have read, it's recomended pass these values as the base class. And my main doubt is, when I pass the object BaseProperties to the factory, all the time do I have to cast the object?
Or what ideas can I implement to model this scenario? Or do I have to have a static Factory where maintain and be used as mapping to the concrete factories?
Thanks in advance.
Define an abstract CreateProblem() in the BaseProperties class. This method can be used generically to allow each concrete Properties subclass to provide its own Factory method.
This is similar to using an instance of WebRequest subclass and calling GetResponse() on it and it then returns the coresponding subclass of WebResponse.
This distributed abstract factory approach allows you to add property/problem pairs easily to the system because the code to map the two is solely contained in those two classes.
You could also use a full Abstract Factory implementation where you have PropertyProblemFactory that defines a CreateProperties() and a CreateProblem(). So in your example you would have AdditionFactory that knows how to create the matching set. But this forces you to define an additional class for each Property/Problem pair. It also works best when you have a class that uses the current/selected PropertyProblemFactory, creates a Properties with it, and then immediately uses that same PropertyProblemFactory factory to create the matching Problem. Once you let go of the reference to the factory and solely have just a reference to the Properties, it is harder to re-locate the right factory to create the Problem. (This can be addressed with yet another class to map object types to factories, but the complexity rises. So the first appoach I suggested is better in this kind of situation).
There are multiple solutions for this. It just depends on how you want to program it.
abstract methods in the abstract class must be handled in all classes that inherit from the abstract class. This way you can easily call abstract methods in the factory without casting.
However when you need to use lots of data from just one specific class then it would not be wise to make abstract methods for it and you should just simply cast the object.
So it all depends on how much classes inherit from BaseProperties and how much data in those classes are the same.

Understanding Interfaces

I am still having trouble understanding what interfaces are good for. I read a few tutorials and I still don't know what they really are for other then "they make your classes keep promises" and "they help with multiple inheritance".
Thats about it. I still don't know when I would even use an interface in a real work example or even when to identify when to use it.
From my limited knowledge of interfaces they can help because if something implements it then you can just pass the interface in allowing to pass in like different classes without worrying about it not being the right parameter.
But I never know what the real point of this since they usually stop short at this point from showing what the code would do after it passes the interface and if they sort of do it it seems like they don't do anything useful that I could look at and go "wow they would help in a real world example".
So what I guess I am saying is I am trying to find a real world example where I can see interfaces in action.
I also don't understand that you can do like a reference to an object like this:
ICalculator myInterface = new JustSomeClass();
So now if I would go myInterface dot and intellisense would pull up I would only see the interface methods and not the other methods in JustSomeClass. So I don't see a point to this yet.
Also I started to do unit testing where they seem to love to use interfaces but I still don't understand why.
Like for instance this example:
public AuthenticationController(IFormsAuthentication formsAuth)
{
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
}
public class FormsAuthenticationWrapper : IFormsAuthentication
{
public void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
public IFormsAuthentication FormsAuth
{
get;
set;
}
Like why bother making this interface? Why not just make FormsAuthenticationWrapper with the methods in it and call it a day? Why First make an interface then have the Wrapper implement the interface and then finally write the methods?
Then I don't get what the statement is really saying.
Like I now know that the statement is saying this
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
if formsAuth is null then make a new FormsAuthenticationWrapper and then assign it to the property that is an Interface.
I guess it goes back to the whole point of why the reference thing. Especially in this case since all the methods are exactly the same. The Wrapper does not have any new methods that the interface does not have and I am not sure but when you do this the methods are filled right(ie they have a body) they don't get converted to stubs because that would really seem pointless to me(it it would be converted back to an interface).
Then in the testing file they have:
var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>();
So they just pass in the FormsAuthentication what I am guessing makes all the fake stubs. I am guessing the wrapper class is used when the program is actually running since it has real methods that do something(like sign a person out).
But looking at new Mock(from moq) it accepts a class or an interface. Why not just again made the wrapper class put those methods in and then in the new Mock call that?
Would that not just make the stubs for you?
Ok, I had a hard time understanding too at first, so don't worry about it.
Think about this, if you have a class, that lets say is a video game character.
public class Character
{
}
Now say I want to have the Character have a weapon. I could use an interface to determin the methods required by a weapon:
interface IWeapon
{
public Use();
}
So lets give the Character a weapon:
public class Character
{
IWeapon weapon;
public void GiveWeapon(IWeapon weapon)
{
this.weapon = weapon;
}
public void UseWeapon()
{
weapon.Use();
}
}
Now we can create weapons that use the IWeapon interface and we can give them to any character class and that class can use the item.
public class Gun : IWeapon
{
public void Use()
{
Console.Writeline("Weapon Fired");
}
}
Then you can stick it together:
Character bob = new character();
Gun pistol = new Gun();
bob.GiveWeapon(pistol);
bob.UseWeapon();
Now this is a general example, but it gives a lot of power. You can read about this more if you look up the Strategy Pattern.
Interfaces define contracts.
In the example you provide, the ?? operator just provides a default value if you pass null to the constructor and doesn't really have anything to do with interfaces.
What is more relevant is that you might use an actual FormsAuthenticationWrapper object, but you can also implement your own IFormsAuthentication type that has nothing to do with the wrapper class at all. The interface tells you what methods and properties you need to implement to fulfill the contract, and allows the compiler to verify that your object really does honor that contract (to some extent - it's simple to honor a contract in name, but not in spirit), and so you don't have to use the pre-built FormsAuthenticationWrapper if you don't want to. You can build a different class that works completely differently but still honors the required contract.
In this respect interfaces are much like normal inheritance, with one important difference. In C# a class can only inherit from one type but can implement many interfaces. So interfaces allow you to fulfill multiple contracts in one class. An object can be an IFormsAuthentication object and also be something else, like IEnumerable.
Interfaces are even more useful when you look at it from the other direction: they allow you to treat many different types as if they were all the same. A good example of this is with the various collections classes. Take this code sample:
void OutputValues(string[] values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This accepts an array and outputs it to the console. Now apply this simple change to use an interface:
void OutputValues(IEnumerable<string> values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This code still takes an array and outputs it to the console. But it also takes a List<string> or anything else you care to give it that implements IEnumerable<string>. So we've taken an interface and used it to make a simple block of code much more powerful.
Another good example is the ASP.Net membership provider. You tell ASP.Net that you honor the membership contract by implementing the required interfaces. Now you can easily customize the built-in ASP.Net authentication to use any source, and all thanks to interfaces. The data providers in the System.Data namespace work in a similar fashion.
One final note: when I see an interface with a "default" wrapper implementation like that, I consider it a bit of an anit-pattern, or at least a code smell. It indicates to me that maybe the interface is too complicated, and you either need to split it apart or consider using some combination of composition + events + delegates rather than derivation to accomplish the same thing.
Perhaps the best way to get a good understanding of interfaces is to use an example from the .NET framework.
Consider the following function:
void printValues(IEnumerable sequence)
{
foreach (var value in sequence)
Console.WriteLine(value);
}
Now I could have written this function to accept a List<T>, object[], or any other type of concrete sequence. But since I have written this function to accept a parameter of type IEnumerable that means that I can pass any concrete type into this function that implements the IEnumerable interface.
The reason this is desirable is that by using the interface type your function is more flexible than it would otherwise be. Also you are increasing the utility of this function as many different callers will be able to make use of it without requiring modification.
By using an interface type you are able to declare the type of your parameter as a contract of what you need from whatever concrete type is passed in. In my example I don't care what type you pass me, I just care that I can iterate it.
All of the answers here have been helpful and I doubt I can add anything new to the mix but in reading the answers here, two of the concepts mentioned in two different answers really meshed well in my head so I will compose my understanding here in the hopes that it might help you.
A class has methods and properties and each of the methods and properties of a class has a signature and a body
public int Add(int x, int y)
{
return x + y;
}
The signature of the Add method is everything before the first curly brace character
public int Add(int x, int y)
The purpose of the method signature is to assign a name to a method and also to describe it's protection level (public, protected, internal, private and / or virtual) which defines where a method can be accessed from in code
The signature also defines the type of the value returned by the method, the Add method above returns an int, and the arguments a method expects to have passed to it by callers
Methods are generally considered to be something an object can do, the example above implies that the class the method is defined in works with numbers
The method body describes precisly (in code) how it is that an object performs the action described by the method name. In the example above the add method works by applying the addition operator to it's parameters and returing the result.
One of the primary differences between an interface and a class in terms of language syntax is that an interface can only define the signature of a methd, never the method body.
Put another way, an interface can describe in a the actions (methods) of a class, but it must never describe how an action is to be performed.
Now that you hopefully have a better understanding of what an interface is, we can move on to the second and third parts of your question when, and why would we use an interface in a real program.
One of the main times interfaces are used in a program is when one wants to perform an action, without wanting to know, or be tied to the specifics of how those actions are performed.
That is a very abstract concept to grapsp so perhaps an example might help to firm things up in your mind
Imagine you are the author of a very popular web browser that millions of people use every day and you have thousands of feature requests from people, some big, some little, some good and some like "bring back <maquee> and <blink> support".
Because you only have a relitivly small number of developers, and an even smaller number of hours in the day, you can't possibly implement every requested feature yourself, but you still want to satisfy your customers
So you decide to allow users to develop their own plugins, so they can <blink 'till the cows come home.
To implement this you might come up with a plugin class that looks like:
public class Plugin
{
public void Run (PluginHost browser)
{
//do stuff here....
}
}
But how could you reasonably implement that method? You can't possibly know precisly how every poossible future plugin is going to work
One possible way around this is to define Plugin as an interface and have the browser refer to each plugin using that, like this:
public interface IPlugin
{
void Run(PluginHost browser);
}
public class PluginHost
{
public void RunPlugins (IPlugin[] plugins)
{
foreach plugin in plugins
{
plugin.Run(this);
}
}
}
Note that as discussed earlier the IPlugin interface describes the Run method but does not specify how Run does it's job because this is specific to each plugin, we don't want the plugin host concerned with the specifics of each individual plugin.
To demonstrate the "can-be-a" aspect of the relationship between a class and an interface I will write a plugin for the plugin host below that implements the <blink> tag.
public class BlinkPlugin: IPlugin
{
private void MakeTextBlink(string text)
{
//code to make text blink.
}
public void Run(PluginHost browser)
{
MakeTextBlink(browser.CurrentPage.ParsedHtml);
}
}
From this perspective you can see that the plugin is defined in a class named BlinkPlugin but because it also implements the IPlugin interface it can also be refered to as an IPlugin object,as the PluginHost class above does, because it doesn't know or care what type the class actually is, just that it can be an IPlugin
I hope this has helped, I really didnt intend it to be quite this long.
I'll give you an example below but let me start with one of your statements. "I don't know how to identify when to use one". to put it on edge. You don't need to identify when to use it but when not to use it. Any parameter (at least to public methods), any (public) property (and personally I would actually extend the list to and anything else) should be declared as something of an interface not a specific class. The only time I would ever declare something of a specific type would be when there was no suitable interface.
I'd go
IEnumerable<T> sequence;
when ever I can and hardly ever (the only case I can think off is if I really needed the ForEach method)
List<T> sequence;
and now an example. Let's say you are building a sytem that can compare prices on cars and computers. Each is displayed in a list.
The car prices are datamined from a set of websites and the computer prices from a set of services.
a solution could be:
create one web page, say with a datagrid and Dependency Injection of a IDataRetriever
(where IDataRetriver is some interface making data fetching available with out you having to know where the data came from (DB,XML,web services or ...) or how they were fetched (data mined, SQL Quering in house data or read from file).
Since the two scenarios we have have nothing but the usage in common a super class will make little sense. but the page using our two classes (one for cars and one for computers) needs to perform the exact same operations in both cases to make that possible we need to tell the page (compiler) which operations are possible. We do that by means of an interface and then the two classes implement that interfcae.
using dependency injection has nothing to do with when or how to use interfaces but the reason why I included it is another common scenario where interfaces makes you life easier. Testing. if you use injection and interfaces you can easily substitute a production class for a testing class when testing. (This again could be to switch data stores or to enforce an error that might be very hard to produce in release code, say a race condition)
We use interfaces (or abstract base classes) to allow polymorphism, which is a very central concept in object-oriented programming. It allows us to compose behavior in very flexible ways. If you haven't already, you should read Design Patterns - it contains numerous examples of using interfaces.
In relation to Test Doubles (such as Mock objects), we use interfaces to be able to remove functionality that we currently don't want to test, or that can't work from within a unit testing framework.
Particularly when working with web development, a lot of the services that we rely on (such as the HTTP Context) isn't available when the code executes outside of the web context, but if we hide that functionality behind an interface, we can replace it with something else during testing.
The way I understood it was:
Derivation is 'is-a' relationship e.g., A Dog is an Animal, A Cow is an Animal but an interface is never derived, it is implemented.
So, interface is a 'can-be' relationship e.g., A Dog can be a Spy Dog, A Dog can be a Circus Dog etc. But to achieve this, a dog has to learn some specific things. Which in OO terminology means that your class has to able to do some specific things (contract as they call it) if it implements an interface. e.g., if your class implements IEnumerable, it clearly means that your class has (must have) such a functionality that it's objects can be Enumerated.
So, in essence, through Interface Implementation a Class exposes a functionality to its users that it can do something and it is NOT inheritance.
With almost everything written about interfaces, let me have a shot.
In simple terms, interface is something which will relate two or more , otherwise, non related classes.
Interfaces define contract which ensures that any two or more classes, even if not completely related, happens to implement a common interface, will contain a common set of operations.
Combined with the support of polymorphism , one can use interfaces to write cleaner and dynamic code.
eg.
Interface livingBeings
-- speak() // says anybody who IS a livingBeing need to define how they speak
class dog implements livingBeings
--speak(){bark;} // implementation of speak as a dog
class bird implements livingBeings
--speak(){chirp;}// implementation of speak as a bird
ICalculator myInterface = new JustSomeClass();
JustSomeClass myObject = (JustSomeClass) myInterface;
Now you have both "interfaces" to work with on the object.
I am pretty new to this too, but I like to think of interfaces as buttons on a remote control. When using the ICalculator interface, you only have access to the buttons (functionality) intended by the interface designer. When using the JustSomeClass object reference, you have another set of buttons. But they both point to the same object.
There are many reasons to do this. The one that has been most useful to me is communication between co-workers. If they can agree on an interface (buttons which will be pushed), then one developer can work on implementing the button's functionality and another can write code that uses the buttons.
Hope this helps.

invoking method declaration without reflection

I have a base class (order) with a set of sub classes (productorder, specialorder, partsorder etc).
Only Some of these sub classes implement a particular interface (ITrackingCustomer) which has a single method declaration (object getcustdetails()).
As part of my solution all of my orders are processed in a central place, i.e. any crud methods pass through a central layer. Within this central layer I want to do the following:
If order is of type ITrackingCustomer
Then invoke method getcustdetails()
I have this working using the following code:
if (typeof(ITrackingCustomer).IsAssignableFrom(Order.GetType()))
{
MethodInfo theMethod = Order.GetType().GetMethod("getcustdetails");
object y = theMethod.Invoke(Order, null);
}
I am happy with the first part using isassignablefrom but would like to use a less performance intensive method for the second part (i.e. the reflection using invoke).
My question is:
Is there a more efficient way of doing this as I have read that using the invoke command is costly.
ITrackingCustomer ord = Order as ITrackingCustomer;
if (ord != null)
{
object y = ord.getcustdetails();
}
You can do:
if(Order is ITrackingCustomer) {
((ITrackingCustomer)Order).getcustdetails();
}
As others have mentioned, you can use the is and as operators to determine if an object is of a certain type. However, polymorphism is usually better suited for solving this type of problem.
If it is feasible, perhaps you can place a getcustdetails() method on Order. Make it virtual if it has a suitable default implementation (i.e. return no details or null), or abstract if it makes sense that all Order types must implement it. Since you have the ITrackingCustomer interface, I suspect that an abstract method won't work well. However, for Order types that implement ITrackingCustomer, you can then implement getcustdetails() accordingly.
At this point, it sounds like you would be able to do away with ITrackingCustomer, but I can't say for certain without knowing more details about how this interface is used.
Once this is done, you won't need to perform any type checks since calling Order.getcustdetails() always dispatches to the correct concrete implementation.
If you are trying to do call by name instead of invoking a member in an interface and you want to be able to call the same method thousands of times, then other than a cast (which I assume you can't do because you don't know the type) or reflection is to JIT compile the call.
Rick Strahl has a nice blog article on the performance costs of various ways to call method and the comments lead to this article which shows how to pull a delegate out to a non-virtual method.
Finally, I wrote a blog article on how to build adapter classes on the fly. What you can do with that is make a directly callable object that meets an abstract class:
public abstract class CustomerDetailsGetter {
public abstract object getcustdetails();
}
// ...
AdapterCompiler compiler = new AdapterCompiler();
AdapterFactory<CusomterDetailsGetter> factory = compiler.DefineAdapter<CustomerDetailsGetter>(Order.GetType());
// now, my code assumes you want to construct an object from whole cloth
// but the code could be changed to invoke the default constructor and set the
// adapted object.
CustomerDetailsGetter getter = factory.Construct(null)
object info = getter.getcustdetails();
Now, I need to be clear - there are only two reasons to do this:
you want to be able to have call-by-name semantics when you know the target arguments at compile time and you don't know have the target assembly, and you want your code to be CLEAN. An example of this is code that knows it wants to create and use a particular object, but doesn't know if the assembly will be available until run time and is forbidden to have a reference.
you want to call object methods a la reflection, but want to do this fast, fast, fast and will be calling them thousands or millions of times.
If it's a "call once" thing, you're way better off writing a helper method to do what you want.

Categories

Resources