Delegate factory
This commit is contained in:
56
PatternDemoCore/Program.cs
Normal file
56
PatternDemoCore/Program.cs
Normal file
@ -0,0 +1,56 @@
|
||||
using Autofac;
|
||||
using System;
|
||||
|
||||
namespace PatternDemoCore
|
||||
{
|
||||
|
||||
public class Service
|
||||
{
|
||||
public string DoSomething(int value)
|
||||
{
|
||||
return $"I have {value}";
|
||||
}
|
||||
}
|
||||
|
||||
public class DomainObject
|
||||
{
|
||||
private readonly Service service;
|
||||
private readonly int value;
|
||||
|
||||
public delegate DomainObject Factory(int value);
|
||||
|
||||
public DomainObject(Service service, int value)
|
||||
{
|
||||
this.service = service;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return service.DoSomething(value);
|
||||
}
|
||||
}
|
||||
|
||||
public class Demo
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
var cb = new ContainerBuilder();
|
||||
cb.RegisterType<Service>();
|
||||
cb.RegisterType<DomainObject>();
|
||||
|
||||
var container = cb.Build();
|
||||
var dobj = container.Resolve<DomainObject>(
|
||||
new PositionalParameter(1, 42));
|
||||
Console.WriteLine(dobj);
|
||||
|
||||
// Better way
|
||||
|
||||
var factory = container.Resolve<DomainObject.Factory>();
|
||||
var dobj2 = factory(42);
|
||||
Console.WriteLine(dobj2);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user