Add project files.
This commit is contained in:
40
FactoryPattern/Factories/GenerateClassWithDataFactory.cs
Normal file
40
FactoryPattern/Factories/GenerateClassWithDataFactory.cs
Normal file
@ -0,0 +1,40 @@
|
||||
using FactoryPattern.Samples;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FactoryPattern.Factories;
|
||||
|
||||
public static class GenerateClassWithDataFactoryExtension
|
||||
{
|
||||
public static void AddGenericClassWithDataFactory(this IServiceCollection services)
|
||||
{
|
||||
services.AddTransient<IUserData, UserData>();
|
||||
services.AddSingleton<Func<IUserData>>(x => () => x.GetService<IUserData>()!);
|
||||
services.AddSingleton<IUserDataFactory, UserDataFactory>();
|
||||
}
|
||||
}
|
||||
|
||||
public interface IUserDataFactory
|
||||
{
|
||||
IUserData Create(string name);
|
||||
}
|
||||
|
||||
public class UserDataFactory : IUserDataFactory
|
||||
{
|
||||
private readonly Func<IUserData> _factory;
|
||||
|
||||
public UserDataFactory(Func<IUserData> factory)
|
||||
{
|
||||
_factory = factory;
|
||||
}
|
||||
|
||||
public IUserData Create(string name)
|
||||
{
|
||||
var output = _factory();
|
||||
output.Name = name;
|
||||
return output;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user