Unity DI Factory
It's pretty simple to register a factory with a unity container:
public class SomeSample{ public string Name { get; set; } public string Description { get; set; } = "default description";}
container.RegisterFactory<SomeSample>(s => new SomeSample { Name = "Test", Description = "Test description" });
The unity container now knows the above factory when used in a constructor. Creating an instance of “SomeSample” with the same data is not very useful for a factory.
A factory with more options:
static void Main(string[] args){ var container = new UnityContainer(); container.RegisterType<SomeSample>(); container.RegisterType<Example>(); container.RegisterFactory<Func<string, SomeSample>>((c, t, s) => new Func<string, SomeSample>(n => { var sample = c.Resolve<SomeSample>(); sample.Name = n; return sample; }) ); container.Resolve<Example>();}
And the example class:
public class Example{ public Example(Func<string, SomeSample> sample) { var result = sample("example one"); Console.WriteLine($"{result.Name} - {result.Description}"); result = sample("More data"); Console.WriteLine($"{result.Name} - {result.Description}"); }}
This factory is more practical since we can provide specific parameters and then determine what to do before returning an instance.
This simple example is an excellent place to start if you need to register a unity factory in a real-world application.