Delegate factory

This commit is contained in:
2020-11-29 20:31:07 +01:00
parent 7cf622179c
commit e7cebf1563
3 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="6.0.0" />
</ItemGroup>
</Project>

View 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);
}
}
}