Dependency injection in nested dynamic object creation? - c#

I have a quite complex application with objects that are nested quite deep from Main and I would like to avoid passing all the dependencies down from the top-level objects and down to the bottom where it might be needed / used.
This is some sample code to illustrate, but is very simplified:
internal class Program
{
public interface IPriceList
{
double GetPrice();
}
public class PriceList : IPriceList
{
public double GetPrice() { return 4.3; }
}
public abstract class Condition
{
public abstract bool IsTrue();
}
public class A
{
private List<Condition> _conditions = new List<Condition>();
public A()
{
}
public void CreateConditionsFromJson()
{
// Read from JSON and dynamically create conditions (not as simple as below)
_conditions.Add(new PriceIsHigherCondition(3.4, ???))
}
}
public class PriceIsHigherCondition : Condition
{
double _price;
IPriceList _priceLIst;
public PriceIsHigherCondition(double price, IPriceList priceList)
{
_price = price;
_priceLIst = priceList;
}
public override bool IsTrue()
{
return _price > _priceLIst.GetPrice();
}
}
static void Main(string[] args)
{
// A is not created here, but deeper down
}
}
It's tempting to create a static class, set the member variables in Main and then access it in the constructors at the bottom level (the condition):
public static class ConditionDependencies
{
public static IPriceList PriceList { get; set; }
}
Any more elegant solution?

I kind of like this (even it might be an anti-pattern):
Define a public static class for dependencies:
public static class ConditionDependencies
{
public static IPriceList PriceList { get; set; }
}
In Main, setup the dependencies:
static void Main(string[] args)
{
// Setup dependencies
ConditionDependencies.PriceList = new PriceList();
}
In a constructor anywhere needing a dependency, just get it:
public class PriceIsHigherCondition : Condition
{
double _price;
IPriceList _priceLIst;
public PriceIsHigherCondition(double price)
{
// Inject Dependencies
_priceLIst = ConditionDependencies.PriceList;
_price = price;
}
public override bool IsTrue()
{
return _price > _priceLIst.GetPrice();
}
}
Is it an anti-pattern? Why? What are the pitfalls?

Related

.NET - It is possible to use DI with the State Pattern?

I'm studying design patterns in .NET and currently i'm trying to implement the State Pattern. But today i got to a problem and i can't figure out how to fix this situation.
I have some state classes, all of them implementing the state interface. One of the last states should connect to a data base, through a service injected by the .NET API Startup class, to persist the data and finish up the process.
The problem is... because of the dependency injection that i need to be in the final state, i can't instanciate this state object to progress to this point. I don't know how to continue from there. I don't know if i'm using the pattern wrong or if the use of dependency injection in this pattern is the problem. I can't give all the details of the problem because my studie's project is a little big mess at this moment, so i made a quick mimic of the structure i'm trying to build in my application.
States interface and the OperatingClass who will execute the state behaviour:
public interface IOperationState
{
public int ExecuteOperation(OperatingClass operatingClass);
}
public class OperatingClass
{
public IOperationState OperationState { get; set; }
public int id { get; set; }
public double value { get; set; }
public OperatingClass(int id) //constructor
{
this.id = id;
value = 0;
OperationState = new StartingState();
}
public int Execute()
{
return OperationState.ExecuteOperation(this);
}
}
Main Service: is the service who my controller calls after receive the API Post Method:
public class MainService
{
public int ExecuteFullOperation(int id)
{
//Receives an id and execute the state transition till the end;
var operatingClass = new OperatingClass(id);
return operatingClass.Execute();
}
}
The classes who represents the states and do the respective actions:
public class StartingState : IOperationState
{
public int ExecuteOperation(OperatingClass operatingClass)
{
// Do something...
operatingClass.OperationState = new MiddleState();
return operatingClass.Execute();
}
}
public class MiddleState : IOperationState
{
public int ExecuteOperation(OperatingClass operatingClass)
{
//Do something with the value... let's supose the result is 123, but it does not matter rn;
operatingClass.value = 123;
//Here is the problem: FinalState needs the PersistenceService, who
//receives a injected class to acess the database;
operatingClass.OperationState = new FinalState();
//I want to execute it and return the sucess or failure of the persistence.
return operatingClass.Execute();
}
}
public class FinalState : IOperationState
{
private readonly IPersistenceService PersistenceService;
public FinalState(IPersistenceService persistenceService)
{
PersistenceService = persistenceService;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
return PersistenceService.PersistData(operatingClass.id, operatingClass.value) ? 200 : 503;
}
}
Additional info: i made the PersistenceService be injected in the Startup.cs as a Transient (i dont know how to make it in another way at this moment).
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPersistenceService, PersistenceService>();
// Irrelevant configurations for the question.
services.AddControllers();
}
Please, help me if you can. I'm having a hard time trying to figure it out by myself.
Thank you for your patience and for your time reading it.
Firstly, we need some simple factory which will supply all necessary dependencies by their type. So let's create types for states:
public enum StateType
{
Start,
Middle,
Final
}
And simple factory:
public class StateFactory
{
private Dictionary<StateType, IOperationState> _stateByType;
// you can inject these dependencies through DI like that:
// public StateFactory(StartingState startingState,
// MiddleState middleState, FinalState finalState,
// PersistenceService persistenceService)
public StateFactory()
{
_stateByType = new Dictionary<StateType, IOperationState>()
{
{ StateType.Start, new StartingState(this) },
{ StateType.Middle, new MiddleState(this) },
{ StateType.Final, new FinalState(new PersistenceService()) }
};
}
public IOperationState GetByType(StateType stateType) =>
_stateByType[stateType];
}
Then we should register all our dependencies:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IPersistenceService, PersistenceService>();
services.AddTransient<StartingState>();
services.AddTransient<MiddleState>();
services.AddTransient<FinalState>();
services.AddTransient<MainService>();
services.AddTransient<OperatingClass>();
services.AddTransient<PersistenceService>();
services.AddTransient<StateFactory>();
}
Our states would look like this:
public class StartingState : IOperationState
{
private StateFactory _factory;
public StartingState(StateFactory stateFactory)
{
_factory = stateFactory;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
// Do something...
// operatingClass.OperationState = new MiddleState();
operatingClass.OperationState = _factory.GetByType(StateType.Middle);
return operatingClass.Execute();
}
}
And MiddleState would look like this:
public class MiddleState : IOperationState
{
private StateFactory _factory;
public MiddleState(StateFactory stateFactory)
{
_factory = stateFactory;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
//Do something with the value... let's supose the result is 123,
// but it does not matter rn;
operatingClass.value = 123;
//Here is the problem: FinalState needs the PersistenceService, who
//receives a injected class to acess the database;
operatingClass.OperationState = _factory.GetByType(StateType.Final);
//I want to execute it and return the sucess or failure of the persistence.
return operatingClass.Execute();
}
}
And Final state should look like this:
public class FinalState : IOperationState
{
private readonly IPersistenceService _persistenceService;
public FinalState(IPersistenceService persistenceService)
{
_persistenceService = persistenceService;
}
public int ExecuteOperation(OperatingClass operatingClass)
{
return _persistenceService
.PersistData(operatingClass.id, operatingClass.value)
? 200
: 503;
}
}
And other classes sush as OperatingClass would use StateFactory too:
public class OperatingClass
{
public IOperationState OperationState { get; set; }
public int id { get; set; }
public double value { get; set; }
public OperatingClass(int id, StateFactory stateFactory) //constructor
{
this.id = id;
value = 0;
// OperationState = new StartingState();
OperationState = stateFactory.GetByType(StateType.Start);
}
public int Execute()
{
return OperationState.ExecuteOperation(this);
}
}
And it is necessary to create concrete example of PersistenceService:
public interface IPersistenceService
{
bool PersistData(int id, double value);
}
public class PersistenceService : IPersistenceService
{
public bool PersistData(int id, double value)
{
throw new NotImplementedException();
}
}

C# reuse instance method

I have 3 classes that have instance functions that are completely identical. Is there any way to reuse these instance methods or should I have a copy in all 3 classes e.g.
public class myclass1
{
public string METHOD;
public string RATE;
public string QTY;
void parseFunctionA()
{
}
void parseFunctionB()
{
}
void parseFunctionC()
{
}
}
public class MYCLASS2
{
public string PRICE;
public string WEIGHT;
void parseFunctionA()
{
}
void parseFunctionB()
{
}
void parseFunctionC()
{
}
}
For me two most popular ways would be to do it using:
Inheritance:
public class Program
{
public static void Main(string[] args)
{
var one = new myclass1();
var two = new myclass2();
one.parseFunctionA();
two.parseFunctionC()
}
// Common class can be abstract if you do want to
// prevent it to be instantiated by itself (prevents var common = new Common())
public class Common
{
// Methods made public only for example usage in Main
public void parseFunctionA()
{
}
public void parseFunctionB()
{
}
public void parseFunctionC()
{
}
}
public class myclass1 : Common
{
public string METHOD;
public string RATE;
public string QTY;
}
public class myclass2 : Common
{
public string PRICE;
public string WEIGHT;
}
}
Or composition:
public class Program
{
public static void Main(string[] args)
{
var common = new Common();
var one = new myclass1(common);
var two = new myclass2(common);
}
public class Common
{
public void parseFunctionA()
{
}
public void parseFunctionB()
{
}
public void parseFunctionC()
{
}
}
public class myclass1
{
private Common _common;
public myclass1(Common common)
{
_common = common;
}
public string METHOD;
public string RATE;
public string QTY;
// use _common as you see fit, in methods, in properties, etc.
}
public class myclass2
{
private Common _common;
public myclass2(Common common)
{
_common = common;
}
public string PRICE;
public string WEIGHT;
// use _common as you see fit, in methods, in properties, etc.
}
}
There are also other methods mentioned in comments under your original post.
Mind that there are no safety features in this example.

C# instantiate class with varying "child" class

I have a class that has some derived classes. That works.
I want to instantiate the "parent" class. Got that far...
But I want to instantiate it with one of the "child" classes, and then possibly change that "child" class later. Maybe the deriving is inappropriate here.
Take the following example:
public class Unicorn {
public string Horn { get; set; }
public Unicorn(){
}
}
public class BadUnicorn : Unicorn{
public string Rainbow()
{
return "dark rainbow";
}
}
public class GoodUnicorn : Unicorn{
public string Rainbow()
{
return "light rainbow";
}
}
I could instantiate one of the children, but then if I change one from "good" to "bad", I would have to re-instantiate. And maybe that's just the way it is, and that would be an acceptable answer if that's all there is to it.
I rather want to instantiate a Unicorn, and then be able to change it from Good to Bad to maintain information stored on that Unicorn, but have access to the current methods and properties of the "child" class.
That way when I call Unicorn.Rainbow() it calls the desired method of the "child" class.
I'm a little new to C#, is there a pattern that fits this bill?
You can't do what you want with polymorphism. You cannot change an instance of class from one to another. Once it is created it is always the same type.
You can use composition though.
Here's what you'd need to do:
public class Unicorn
{
public string Horn { get; set; }
public Unicorn(Rainbow rainbow)
{
_rainbow = rainbow;
}
public void SetRainbow(Rainbow rainbow)
{
_rainbow = rainbow;
}
private Rainbow _rainbow;
public string Rainbow()
{
return _rainbow.Colour();
}
}
public abstract class Rainbow
{
public abstract string Colour();
}
public class BadRainbow : Rainbow
{
public override string Colour()
{
return "dark rainbow";
}
}
public class GoodRainbow : Rainbow
{
public override string Colour()
{
return "light rainbow";
}
}
You can test like this:
var unicorn = new Unicorn(new GoodRainbow());
Console.WriteLine(unicorn.Rainbow());
unicorn.SetRainbow(new BadRainbow());
Console.WriteLine(unicorn.Rainbow());
This outputs:
light rainbow
dark rainbow
The instance of Unicorn stays the same, but you can change the rainbow.
Here's my take on delegate dictionary. While it seems superfluous to use Func instead of just string, if the method have additional functionality like calculation or need parameters, you're covered with Func.
public class Unicorn
{
static Dictionary<Attitude, Func<string>> RainbowByAttitude =
new Dictionary<Attitude, Func<string>>()
{
[Attitude.Bad] = new Func<string>(() => "dark rainbow"),
[Attitude.Good] = new Func<string>(()=>"light rainbow")
};
public string Horn { get; set; }
public enum Attitude
{
Good,Bad
}
public Attitude attitude;
public Unicorn(Attitude attitude)
{
this.attitude = attitude;
}
public string Rainbow() => RainbowByAttitude[attitude].Invoke();
}
class Program
{
static void Main(string[] args)
{
Unicorn unicorn;
unicorn = new Unicorn(Unicorn.Attitude.Bad);
Console.WriteLine(unicorn.Rainbow());
unicorn.attitude = Unicorn.Attitude.Good;
Console.WriteLine(unicorn.Rainbow());
}
}
It seems like a state pattern to me like this:
public abstract class UnicornState
{
public abstract UnicornState Change();
public abstract string Rainbow();
}
public sealed class GoodUnicornState : UnicornState
{
public override UnicornState Change()
{
return new BadUnicornState();
}
public override string Rainbow()
{
return "light rainbow";
}
}
public sealed class BadUnicornState : UnicornState
{
public override UnicornState Change()
{
return new GoodUnicornState();
}
public override string Rainbow()
{
return "dark rainbow";
}
}
public class Unicorn
{
public string Horn { get; set; }
public UnicornState State { get; set; }
public string Rainbow => State.Rainbow();
}
Usage:
var u = new Unicorn();
u.State = new GoodUnicornState();
Console.WriteLine(u.Rainbow);
u.State = u.State.Change();
Console.WriteLine(u.Rainbow);

Interfaces and inheritance with derived class

I am stuck on interfaces and inheritance. If I implement two classes who both have an interface each, how would I be able to add the properties of Class A and B together? For instance I wanted to associate firstitem with the seconditem.
public interface IAlpha
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "/AddBravoToAlpha/{firstitem}/{seconditem}")]
void AddBravoToAlpha(int firstitem, int seconditem);
}
public interface IBravo
{
// what goes in here?
}
public Class Alpha
{
public Alpha()
{
AlphaAdd = new List<Bravo>();
}
int Firstitem { get; set }
public List<Bravo> AlphaAdd { get; set; }
}
public Class Bravo
{
public Bravo()
{
BravoAdd = new List<Alpha>(); //not sure if Bravo can access Alpha (derived class)
}
int Seconditem { get; set }
Guid Indexer { get; set }
public List<Alpha> BravoAdd { get; set; }
}
public Class BravoDoesAlpha : IBravo, IAlpha //????
{
List<Alpha> alpha = new List<Alpha>();
List<Bravo> bravo = new List<Bravo>();
public void AddBravoToAlpha(int firstitem, int seconditem)
{
var result = alpha.Where(n => String.Equals(n.Firstitem, firstitem)).FirstOrDefault();
var result1 = bravo.Where(n => String.Equals(n.Seconditem, seconditem)).FirstOrDefault();
if (result != null)
{
result.BravoAdd.Add(new Alpha() { Firstitem = firstitem });
}
if (result1 != null)
{
result1.AlphaAdd.Add(new Bravo() { Seconditem = seconditem });
}
}
}
Okay, so the question you are being asked is basically one about how to do a certain kind of refactoring known as "extracting" an interface.
This is one of the more easy refactorings to do and to understand if you understand interfaces vs. types.
All interfaces are types, but not all types are interfaces.
Now let's assume we are dealing in a world with two families of types: classes and interfaces (as in your example).
Instead of working your example directly, I will work a different but clearer example that does not use Alpha, Bravo, Charlie, Epsilon, etc. because this kind of stuff makes it harder to see the meaning.
First, here's the before:
public class Dog
{
public void Bark() { Console.WriteLine("Woof!"); }
public int NumberOfDogLegs { get { return 2; } }
public int NumberOfDogFriends { get; set; } // this can be set
private string SecretsOfDog { get; set; } // this is private
}
public class DoorBell
{
public void Chime() { Console.WriteLine("Ding!"); }
}
To extract the interface of a class, simply, well, extract all the public members of the class to an interface.
public interface IDog
{
void Bark();
int NumberOfDogLegs { get; }
int NumberOfDogFriends { get; set; }
}
public interface IDoorBell
{
void Chime();
}
Now to really make use of OOP, you can find a way to abstract IDog and IDoorBell. What do they have in common? Well, the obvious one is they both make a noise. So we make a new interface, public interface IMakeANoise and say that IDog and IDoorBell both implement it.
public interface IMakeANoise
{
void MakeNoise();
}
public interface IDog : IMakeANoise
{
void Bark();
int NumberOfDogLegs { get; }
int NumberOfDogFriends { get; set; }
}
public interface IDoorBell : IMakeANoise
{
void Chime();
}
And now we have a new method to implement on Dog and DoorBell.
public class Dog : IDog
{
public void Bark() { Console.WriteLine("Woof!"); }
public int NumberOfDogLegs { get { return 2; } }
public int NumberOfDogFriends { get; set; } // this can be set
private string SecretsOfDog { get; set; } // this is private
public void IMakeANoise() { Bark(); }
}
public class DoorBell : IDoorBell
{
public void Chime() { Console.WriteLine("Ding!"); }
public void IMakeANoise() { Chime(); }
}
Now let's say we are actually writing a video game and Dog and DoorBell are both things that we can show on the screen. Well, this makes them a lot bigger because we will need to provide more information like their coordinates, their states, etc.
In this case, Dog and DoorBell may be very different to us but are similar enough to potentially merit sharing a base class. (Really, this is a stretch, but it does get the point across.)
Without adding all those new interfaces and their implementations, let's just do the "sharing a base class" refactoring for what we already have.
public class RenderableThing : IMakeANoise, IDoAThousandOtherThings
{
protected virtual string MyNoiseToMake { get { return ""; } }
public virtual void MakeANoise()
{
Console.WriteLine(MyNoiseToMake);
}
}
public class Dog : RenderableThing, IDog
{
protected override string MyNoiseToMake { get { return "Woof!"; } }
public void Bark() { MakeANoise(); } // see what we did there?
// Notice that I am not declaring the method MakeANoise because it is inherited and I am using it by overriding MyNoiseToMake
public int NumberOfDogLegs { get { return 2; } }
public int NumberOfDogFriends { get; set; } // this can be set
private string SecretsOfDog { get; set; } // this is private
}
public class DoorBell : RenderableThing, IDoorBell
{
public void Chime() { Console.WriteLine("Ding!"); }
public override void MakeANoise()
{
Chime(); Chime(); Chime(); //I'll do it my own way!
}
}
You may wonder, what's the point? So we can do this...
IMakeANoise dogNoiseMaker = new Dog();
IMakeANoise doorBellNoiseMaker = new DoorBell();
IList<IMakeANoise> listOfNoiseMakers = new List<IMakeANoise>();
listOfNoiseMakers.Add(dogNoiseMaker);
listOfNoiseMakers.Add(doorBellNoiseMaker);
foreach (IMakeANoise noiseMaker in listOfNoiseMakers)
{
noiseMaker.MakeANoise();
}
// This will output
// Woof!
// Ding!
// Ding!
// Ding!
I'm going to take a shot in the dark and venture a guess that you don't quite understand what interfaces and inheritance is. I'll start off by explaining what interfaces are:
Interfaces contain only the definitions of methods, properties, events or indexers that an inheriting class must implement.
For example:
interface IExample
{
void HelloWorld();
}
class ExampleClass : IExample
{
public void HelloWorld()
{
Console.WriteLine("Hello world.");
}
}
Now for Inheritance; when you derive a class from a base class the derived class will inherit all members of the base class except for the constructors. Note: Depending on the accessibility of the members in the base class it's children may or may not be able to access the parents members.
public class Animal
{
public string Name { get; set; }
public Animal(string name)
{
Name = name;
}
public void Talk()
{
Console.WriteLine("{0} is talking", Name);
}
}
public class Cat : Animal
{
public Cat(string name) : base(name) { }
}
public class Dog : Animal
{
public string FurColor { get; set; }
public Dog(string name, string furColor) : base(name)
{
FurColor = furColor;
}
public void Greeting()
{
Console.WriteLine("{0} has {1} fur.", Name, FurColor);
}
}
class Program
{
static void Main(string[] args)
{
var cat = new Cat("Rex");
cat.Talk();
var dog = new Dog("Beanie", "Red");
dog.Talk();
}
}

Access const with generics C#

I have the following base class:
public class Base
{
public string LogicalName { get; set; }
public int NumberOfChars { get; set; }
public Base()
{
}
public Base(string logicalName, int numberOfChars)
{
LogicalName = logicalName;
NumberOfChars = numberOfChars;
}
}
and the following derived classes:
public class Derived1 : Base
{
public const string EntityLogicalName = "Name1";
public const int EntityNumberOfChars = 30;
public Derived1() : base(EntityLogicalName, EntityNumberOfChars)
{
}
}
public class Derived2 : Base
{
public const string EntityLogicalName = "Name2";
public const int EntityNumberOfChars = 50;
public Derived2()
: base(EntityLogicalName, EntityNumberOfChars)
{
}
}
and I also have this function that is provided by a service:
public IEnumerable<T> GetEntities<T>(string entityName, int numberOfChars) where T : Base
{
//Some code to get the entities
}
My problem is how can I call this function generically? I want to call it with something that looks like this:
public void TestEntities<T>() where T : Base
{
var entities = GetEntities<T>(T.EntityLogicalName, T.EntityNumberOfChars);
//some other code to test the entities
}
This of course doesn't work because at this point T is not known. How can I accomplish something similar to this? EntityLogicalName and EntityNumberOfChars are characteristics that all Base derived classes have and they never change for each derived class. Can I get them from the Base class without instantiating objects or some other way that I am not seeing?
Replace constants with getter abstract properties
public abstract class Base
{
public abstract string LogicalName { get; }
public abstract int NumberOfChars { get; }
public Base()
{
}
}
public class Derived1 : Base
{
public string LogicalName { get { return "Name1"; } }
public int NumberOfChars { get { return 30; } }
public Derived1() : base()
{
}
}
Also, you will be able to put some logic into overriden getter, e.g. :
...
public string LogicalName { get { return this.EntityMap.Name; } }
...
UPDATE: The fact that you do not want to instantiate object from class but want to be able to get that string in a strongly typed manner can be handled in one more way. It is totally separate from answer above ( Since you can't override static props in c#). Consider the following code. We are adding one more class here, but LocatorInner can be a member of BaseClass. We are using this approach a lot in several existing apps.:
public class Locator
{
public static class LocatorInner<T> where T : BaseClass
{
public static string Name { get; set; }
}
public static string GetName<T>() where T : BaseClass
{
return LocatorInner<T>.Name;
}
public static void SetName<T>(string name) where T : BaseClass
{
LocatorInner<T>.Name = name;
}
}
public class BaseClass
{
}
public class DerivedClass: BaseClass
{
static DerivedClass()
{
Locator.LocatorInner<DerivedClass>.Name = "me";
}
}
public class TestClass<T> where T : BaseClass
{
public void Method()
{
var name = Locator.GetName<T>();
}
}
IMHO, I believe using constants here is a bad design decision.
You can either solve the issue using #vittore approach, but for me it sounds like you should use meta-programming with attributes if you're looking to get data from the T generic argument
For example, what about:
public class LogicalNameAttribute : Attribute
{
public LogicalNameAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
public class NumberOfCharsAttribute : Attribute
{
public NumberOfCharsAttribute (int number)
{
Number = number;
}
public string Number { get; private set; }
}
[LogicalName("Name1"), NumberOfChars(30)]
public class Derived1 : Base
{
public Derived1() : base()
{
}
}
Now your service method can extract attribute metadata as follows:
public void TestEntities<T>() where T : Base
{
LogicalNameAttribute logicalNameAttr = typeof(T).GetCustomAttribute<LogicalNameAttribute>();
NumberOfCharsAttribute numberOfCharsAttr = typeof(T).GetCustomAttribute<NumberOfCharsAttribute >();
Contract.Assert(logicalNameAttr != null);
Contract.Assert(numberOfCharsAttr != null);
string logicalName = logicalNameAttr.Name;
int numberOfChars = numberOfCharsAttr.Number;
// Other stuff
}
There's a performance penalty because you need to use reflection to get attributes applied to T, but you gain the flexibility of not forcing derived classes to provide this static info.
As #vittore mentioned, move the properties to base,pass the hard coded values from derived and in creation use just defautl(T)
public IEnumerable<T> GetEntities<T>(string entityName, int numberOfChars) where T : Base
{
yield return default(T); //Is its always class use new constraint and return new T();
}

Categories