Home > Mobile >  Creating a generic factory in c# with a parameter
Creating a generic factory in c# with a parameter

Time:03-27

I'm trying to create a very simple factory class in c#. The only snag is that I need to pass a parameter.

Here's my class that I want to create:

public class ClassToCreate
{
    private readonly string myValue;

    public ClassToCreate(string myValue)
    {
        this.myValue = myValue;
    }
}

First I was going to create the factory method like this

public T CreateNewClass<T>(string value) where T : class, new()

but you can't pass a parameter - so I tried this

public class FactoryClass
{
    private object _instance = null;

    public T CreateNewClass<T>(Func<string, T> createWithValue) where T : class
    {
        if (_instance == null)
            _instance = createWithValue(??string here??);

        return (T)_instance;
    }
}

The class that calls it

string somestring = "hello world";
var factory = new FactoryClass();
var myclass = factory.CreateNewClass<ClassToCreate>(_ => new ClassToCreate(somestring));

Ideally the calling code above would just pass the value - but I can't get it to accept anything...

CodePudding user response:

Note that there are alternatives to Activator.CreateInstance which are more performant, but for your basic scenario we could just use it and pass along a parameter (which is injected into the instantiation process as a constructor parameter.

First off we have the factory:

public class FactoryClass
{
    private object _instance = null;

    public T CreateNewClass<T>(string value) where T : class
    {
        if (_instance == null)
        {
            _instance = (T)Activator.CreateInstance(typeof(T), value);
        }
        return (T)_instance;
    }
}

Here is a NUnit test which passes using this approach :

        [Test]
        [TestCase("hullo world")]
        public void CreateNewClassReturnsFieldValue(string greeting)
        {
            var factory = new FactoryClass();
            var instance = factory.CreateNewClass<ClassToCreate>(greeting);
            string myValue = typeof(ClassToCreate).GetField("myValue", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(instance) as string;
            myValue.Should().Be(greeting);
        }

I am looking at a course online with Factory patterns so your question was an interesting one as it is related to the course I am doing right now.

Note - I dropped the new() constraint has this forced me to add a parameterless constructor, which your ClassToCreate lacked anyways.

Unit test

CodePudding user response:

The simplest answer to make this work is to effectively do nothing.

Try this:

public class FactoryClass
{
    private Dictionary<Type, object> _instances = new();

    public T CreateNewClass<T>(Func<T> createWithValue) where T : class
    {
        var success = _instances.TryGetValue(typeof(T), out object instance);
        if (!success)
        {
            instance = createWithValue();
            _instances[typeof(T)] = instance;
        }
        return (T)instance;
    }
}

You can use it like this:

var factory = new FactoryClass();
var instance = factory.CreateNewClass(() => new ClassToCreate("Hello"));

Simple.

Alternatively, you could then define up a bunch of methods that hard code this in for you:

public T CreateNewClass<P, T>(P p, Func<P,T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p));
public T CreateNewClass<P1, P2, T>(P1 p1, P2 p2, Func<P1, P2, T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p1, p2));
public T CreateNewClass<P1, P2, P3, T>(P1 p1, P2 p2, P3 p3, Func<P1, P2, P3, T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p1, p2, p3));
public T CreateNewClass<P1, P2, P3, P4, T>(P1 p1, P2 p2, P3 p3, P4 p4, Func<P1, P2, P3, P4, T> createWithValue) where T : class => this.CreateNewClass<T>(() => createWithValue(p1, p2, p3, p4));
// etc

Now you could call it like this:

var factory = new FactoryClass();
var instance = factory.CreateNewClass("Hello", p => new ClassToCreate(p));

CodePudding user response:

An alternative to trying to create a factory class is to create a more abstract version which allows you to define factories at run-time and separate the factory component from the code that instantiates the instance.

So, this kind of factory can be used like this:

var factory = new AbstractFactoryClass();
factory.Register<string, ClassToCreate>(p => new ClassToCreate(p));
factory.Register<string, int, Person>((name, age) => new Person(name, age));

Then, later in your code, you can write this to actually instantiate your instances:

var instance = factory.Create<string, ClassToCreate>("Hello");
var person = factory.Create<string, int, Person>("Fred", 99);

Here are the classes you need:

public class AbstractFactoryClass
{
    private Dictionary<Type, Delegate> _factories = new();

    public void Register<T>(Func<T> factory) => _factories[typeof(Func<T>)] = factory;
    public void Register<P, T>(Func<P, T> factory) => _factories[typeof(Func<P, T>)] = factory;
    public void Register<P1, P2, T>(Func<P1, P2, T> factory) => _factories[typeof(Func<P1, P2, T>)] = factory;
    public void Register<P1, P2, P3, T>(Func<P1, P2, P3, T> factory) => _factories[typeof(Func<P1, P2, P3, T>)] = factory;

    public T Create<T>() => ((Func<T>)_factories[typeof(Func<T>)])();
    public T Create<P, T>(P p) => ((Func<P, T>)_factories[typeof(Func<P, T>)])(p);
    public T Create<P1, P2, T>(P1 p1, P2 p2) => ((Func<P1, P2, T>)_factories[typeof(Func<P1, P2, T>)])(p1, p2);
    public T Create<P1, P2, P3, T>(P1 p1, P2 p2, P3 p3) => ((Func<P1, P2, P3, T>)_factories[typeof(Func<P1, P2, P3, T>)])(p1, p2, p3);
}

public class ClassToCreate
{
    private readonly string myValue;

    public ClassToCreate(string myValue)
    {
        this.myValue = myValue;
    }

    public override string ToString() => myValue;
}

public class Person
{
    private readonly string name;
    private readonly int age;

    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public override string ToString() => $"{name} is {age} years old";
}

Now, what because incredibly cool with this is that you can use it to instantiate interfaces.

Try with this code:

public interface IFoo
{
    string Name { get; }
}

public class Foo1 : IFoo
{
    private readonly string name;

    public Foo1(string name)
    {
        this.name = name;
    }

    public string Name => name;
}

public class Foo2 : IFoo
{
    private readonly string name;

    public Foo2(string name)
    {
        this.name = name;
    }

    public string Name => name;
}

Now I can register and create interfaces like this:

// during set up
factory.Register<string, IFoo>(n => new Foo1(n));

// somewhere later in my code:
IFoo foo = factory.Create<string, IFoo>("Fred");

I can now easily change my Register call to n => new Foo2(n) and the code that later calls the Create method doesn't change. It just now gets a Foo2.

You can easily swap out different repositories - read from a file or a database - or add a decorator to an interface.

Let try these classes:

public interface IBar
{
    string Name { get; }
}

public class BarCore : IBar
{
    public string Name { get; private set; }

    public BarCore(string name)
    {
        this.Name = name;
    }
}

public class BarDecorator : IBar
{
    private IBar _bar;

    public BarDecorator(IBar bar)
    {
        this._bar = bar;
    }

    public string Name
    {
        get
        {
            Console.WriteLine($"You called Name on {_bar.GetType().Name}");
            return _bar.Name;
        }
    }
}

I could run this like this:

// during set up
factory.Register<string, IBar>(n => new BarCore(n));

// somewhere later in my code:
IBar bar = factory.Create<string, IBar>("Fred");

Console.WriteLine($"{bar.Name} from {bar.GetType().Name}");

I get this output:

Fred from BarCore

But, if I change my registration code to this:

factory.Register<string, IBar>(n => new BarDecorator(new BarCore(n)));

I don't need to change my subsequent code, but when I run it, I now get this:

You called Name on BarCore
Fred from BarDecorator

Instant debugging!

  •  Tags:  
  • c#
  • Related