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

@ -5,6 +5,8 @@ VisualStudioVersion = 16.0.30717.126
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoFacSamles", "AutoFacSamles\AutoFacSamles.csproj", "{2CFA4809-16F7-4DB9-B4BB-CF60945656E5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PatternDemoCore", "PatternDemoCore\PatternDemoCore.csproj", "{D8041EF1-F2AC-4A04-A7A5-56E2CB6F249C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -15,6 +17,10 @@ Global
{2CFA4809-16F7-4DB9-B4BB-CF60945656E5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2CFA4809-16F7-4DB9-B4BB-CF60945656E5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2CFA4809-16F7-4DB9-B4BB-CF60945656E5}.Release|Any CPU.Build.0 = Release|Any CPU
{D8041EF1-F2AC-4A04-A7A5-56E2CB6F249C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D8041EF1-F2AC-4A04-A7A5-56E2CB6F249C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D8041EF1-F2AC-4A04-A7A5-56E2CB6F249C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D8041EF1-F2AC-4A04-A7A5-56E2CB6F249C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

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