Is it possible to specify in a Unity Resolve which constructor Unity should use?
The object I am trying to create may look something like this:
public class MyObject
{
[UseWhenSunny]
public MyObject(InputOne one)
{
Console.WriteLine("Chose constructor one");
}
[UseWhenRaining]
public MyObject(InputTwo two)
{
Console.WriteLine("Chose constructor two");
}
}
public class InputOne
{
}
public class InputTwo
{
}
My construction could be something like this:
var container = new UnityContainer();
container.RegisterInstance(new InputTwo());
var myObject = container.Resolve<MyObject>();
I can find the correct ConstructorInfo easily enough, but I have not figured out how to force Unity to use this specific constructor?
It's a strange construct when you use different constructors for states within a game/program. If you want to pass two different class types, you could use inheritance for that. You need a common ancestor because InputOne and InputTwo only shares Object as common ancestor. So you need to specify a new base class. In this base class you write the common functionality/definition.
Here is an example:
public abstract class InputBase
{
public abstract void Show();
}
public class InputOne : InputBase
{
public override void Show()
{
Console.WriteLine("Show one");
}
}
public class InputTwo : InputBase
{
public override void Show()
{
Console.WriteLine("Show two");
}
}
public class MyObject
{
public MyObject(InputBase input)
{
// because InputOne and InputTwo can be casted to their base class
// they both can be passed as InputBase.
// InputBase defines the Show method which their derived ones must
// implement (abstract).
input.Show();
}
}
See Inheritance (C# Programming Guide)
Related
I am writing a tranformer that takes some input and gives an output.I need to call a specific tranformer based on my input type.
public static myentrypoint( template t);
{
//I could do something like this.
switch(t)
{
case t1:
transformt1(..);
case t2:
transformt1(..);
....
}
}
Trasform1 : Itransform
{
tranform1(...);
}
Trasform2 : Itransform
{
tranform2(...);
}
I need to map which function to call based on what my template is. I can do a switch but are there more cleaner ways to do this using some design patterns ? I was thinking a of writing a static dictionary. I am new to OOP so any suggestions would be great.
If template is a class, and each template potentially has a different transform, then why not just include the transform function inside of your template class?
public static myentrypoint( ITemplate t);
{
t.transform();
}
The way that I do these types of situations is through the use of Generics. (Shameless self-promotion of a blog post)
Basically, you'll have your base class set up like this:
public abstract class Transformer<T>
where T : Template
{
public abstract void Transform(T item);
}
Then you derive for each of your types like this:
public class Transformer1 : Tansformer<Template1>
{
public void Transform(Template1 item)
{
}
}
public class Transformer2 : Transformer<Template2>
{
public void Transform(Template2 item)
{
}
}
Then you'll just need a factory to give you the correct Transformer.
public class TransformFactory
{
public Transformer<T> GetTransformer<T>(T item)
{
if (item is Template1)
return new Transformer1();
else if (item is Template2)
return new Transformer2();
// ...
}
}
The benefit of this approach is that you'll be able to encapsulate all behavior on that specific type in the concrete implementations. If there is any common behavior on them all, you can do that in the abstract base.
Invoking methods based on a parameter without switch-case statements in C#
In OOP, based on the [open/close principle] which says that software entities such as classes and functions should be open for extension, but closed
for modification.
Methods which use switch-case statement would call this principle into question. In order to implement this principle inside the codes without
causing changes in their functionality.
We use a pattern named "Delegate Dictionary Pattern".
For example, we have an entity named Template that keep input values as well as some of Transform classes for processing this Template.
Template class for keeping input value
public class Template
{
public int TransformNo { get; set; }
public string Title { get; set; }
}
ITransform interface for transform abstract
public interface ITransform
{
void Do(Template template);
}
Transform1 as a concrete class of ITransform
public class Transform1 : ITransform
{
public void Do(Template template)
{
Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
}
}
Transform2 as a concrete class of ITransform
public class Transform2 : ITransform
{
public void Do(Template template)
{
Console.WriteLine($"Transform : {template.TransformNo}, TemplateTitle : { template.Title}");
}
}
TransformCordinator class for coordinating template of *ITransformer**
public class TransformCordinator
{
Dictionary<int, Action<Template>> transformMap = new Dictionary<int, Action<Template>>();
public TransformCordinator()
{
transformMap.Add(1, x => new Transform1().Do(x));
transformMap.Add(2, x => new Transform2().Do(x));
}
public void Do(Template template)
{
transformMap[template.TransformNo](template);
}
}
// example
class Program
{
static void Main(string[] args)
{
var transformCordinator = new TransformCordinator();
transformCordinator.Do(new Template() { TransformNo = 1, Title = "Hi!" });
Console.ReadLine();
}
}
My aim is to write an abstract base class which contains a method for deriving “child instances”. In this method already some computation is done which is common in all deriving classes.
The difficulty is that the base class is not able to create the child class on its own. So I introduced a type parameter T in my base class and a protected abstract method which shall return an instance of T.
public abstract class Base<T> where T : Base<T>
{
public T GetChild()
{
string param = ComplexComputation();
return NewInstanceFrom(param);
}
protected abstract T NewInstanceFrom(string param);
}
// --- somewhere else: ---
public class Derivative : Base<Derivative>
{
public Derivative() { }
protected sealed override Derivative NewInstanceFrom(string param)
{
return new Derivative(param);
}
private Derivative(string param)
{
// some configuration
}
}
The disadvantage of this approach is that I cannot ensure that NewInstanceFrom is only invoked by the base class. It could also be invoked by classes inheriting from Derivative. That’s what I want to avoid.
So I could encapsulate the functionality in a private class or delegate:
public abstract class Base<T> where T : Base<T>
{
public T GetChild()
{
string param = ComplexComputation();
return subElementDerivator(param);
}
protected Base<T>(Func<string, T> subElementDerivator)
{
this.subElementDerivator = subElementDerivator;
}
private Func<string, T> subElementDerivator;
}
// --- somewhere else: ---
public class Derivative : Base<Derivative>
{
public Derivative()
: base(deriveSubElement)
{
}
private Derivative(string param)
: base(deriveSubElement)
{
// some configuration
}
private static Derivative deriveSubElement(string param)
{
return new Derivative(param);
}
}
But this introduces a new object.
Is there a simpler way to prevent access to a functionality (which the base class shall have access to) from heirs of Derivative?
You can use explicit interface implementation to hide your factory method. Any client can still call the Create method after casting but at least intellisense won't help developers.
public interface ISecretFactory<T>
{
T Create(string param);
}
public abstract class Base<T> where T : Base<T>, ISecretFactory<T>
{
public T GetChild()
{
// We are sure type T always implements ISecretFactory<T>
var factory = this as ISecretFactory<T>;
return factory.Create("base param");
}
}
public class Derivative : Base<Derivative>, ISecretFactory<Derivative>
{
public Derivative()
{
}
private Derivative(string param)
{
}
Derivative ISecretFactory<Derivative>.Create(string param)
{
return new Derivative(param);
}
}
public class SecondDerivative : Derivative
{
public void F()
{
// intellisense won't show Create method here.
// But 'this as ISecretFactory<Derivative>' trick still works.
}
}
The additional object can be avoided by moving the ComplexComputation to the constructor of the base class and making the GetChild method abstract to let the deriving class pick a correct constructor there.
But how to return the computed value param in base constructor to the invoking derivate constructor? A possibility is to use the out parameter modifier. But because in C# 5.0 we are unfortunately not able to declare the variables before (or within) the base constructor call, we need to take the parameter along in the derivative constructor.
public abstract class Base<T> where T : Base<T>
{
public abstract T GetChild();
protected Base(T parent, out string param)
{
param = ComplexComputation();
}
protected Base()
{
}
}
// --- somewhere else: ---
public class Derivative : Base<Derivative>
{
public sealed override Derivative GetChild()
{
string param;
return new Derivative(this, out param);
}
public Derivative() { }
private Derivative(Derivative parent, out string param)
: base(parent, out param)
{
// some configuration
}
}
In my case I could leave the param from the constructors away, instead I stored it in a public property.
This approach except the pesky necessary hack looks relatively clean to me, but it does not “scale” when multiple overloadings of GetChild are necessary.
Maybe in C# 6.0 it is possible to declare the param directly in the base constructor invocation. https://msdn.microsoft.com/de-de/magazine/dn683793.aspx
I want to force my child classes to pass themselves as as the generic parameter to the parent class.
For example :
class BaseClass<T> where T: BaseClass
{
//FullClassName : Tuple [Save,Update,Delete]
Dictionary<string,Tuple<delegate,delegate,delegate>> dict = new Dictionary...;
static BaseClass()
{
RegisterType();
}
private static void RegisterType()
{
Type t = typeof(T);
var props = t.GetProperties().Where(/* Read all properties with the SomeCustomAttribute */);
/* Create the delegates using expression trees and add the final tuple to the dictionary */
}
public virtual void Save()
{
delegate d = dict[t.GetType().FullName];
d.Item1(this);
}
}
class ChildClass : BaseClass<ChildClass>
{
[SomeCustomAttribute]
public int SomeID {get;set;}
[SomeCustomAttribute]
public string SomeName {get; set;}
}
public class Program
{
public static void Main(string[] args)
{
ChildClass c = new ChildClass();
c.Save();
}
}
Obviously the above code won't compile. I'll restate : I want the child class to pass itself as the generic parameter and not any other child of BaseClass.
(The above code is kind of a psuedo code and will still not compile).
You can do this:
public class BaseClass<T> where T: BaseClass<T> { }
public class ChildClass : BaseClass<ChildClass> { }
But this doesn't force you to use ChildClass as the generic parameter. You could do this public class OtherChildClass : BaseClass<ChildClass> { } which would break the "coontract" that you want to enforce.
The direct answer is that if your accessing a static method then typeof(T) will give you the type for reflection.
However, there is probably better solutions than using reflection. Options:
1) Static constructor on the child class.
2) Abstract method declared in the base class.
I do not know the application, but I get concerned about my design if I feel like using a static constructor, I also get concerned if a base class needs to initialize the child class.
I suggest looking at injection as a solution rather than inheritance. It offers superior unit testing and often a better architecture.
More info (after initial post), this is my preferred solution:
public interface IRegesterable
{
void Register();
}
public class Widget : IRegesterable
{
public void Register()
{
// do stuff
}
}
public class Class1
{
public Class1(IRegesterable widget)
{
widget.Register();
}
}
Hope this helps
The ConcurrentDictionary is being used as a Set<Type>. We can check in the Set<Type> if the type has been initialized. If not we run RegisterType on the type.
public abstract class BaseClass
{
//Concurrent Set does not exist.
private static ConcurrentDictionary<Type, bool> _registeredTypes
= new ConcurrentDictionary<Type, bool>();
protected BaseClass()
{
_registeredTypes.GetOrAdd(GetType(), RegisterType);
}
private static bool RegisterType(Type type)
{
//some code that will perform one time processing using reflections
//dummy return value
return true;
}
}
public class ChildClass : BaseClass
{
}
There are several inefficiencies with this pattern though.
object.GetType() is pretty darn slow, and inefficient.
Even with the HashSet behavior, we are checking for initialization on each instanciation. Its as fast as I can get it, but its still pretty superfluous.
[MAJOR EDITS, my first post was somewhat misleading. My appologies]
Given a class such as:
public class DatabaseResult{
public bool Successful;
public string ErrorMessage;
//Database operation failed
public static DatabaseResult Failed(string message) {
return new DatabaseResult{
Successful = true,
ErrorMessage = message
};
}
}
How can I implement subclasses such that I can add additional properties to represent data relevant to the particular operation (such as MatchedResult in the case of a SELECT type query) without the need to implement that static failure function? If I try to use plain inheritance, the return type will be of the parent class. Eg:
DoThingDatabaseResult : DatabaseResult {
public IEnumerable<object> SomeResultSet;
public static Successful(IEnumerable<object> theResults){
return new DoThingDatabaseResult {
Successful = true,
ErrorMessage = "",
SomeResultSet = theResults
};
}
//public static DatabaseResult Failed exists, but it's the parent type!
}
The goal is to avoid needing to copy the Failed static function for every subclass implementation.
Make it recursively generic:
public class BankAccount<T> where T : BankAccount<T>, new()
{
public T SomeFactoryMethod() { return new T(); }
}
public class SavingsAccount: BankAccount<SavingsAccount>{}
You'll note that I made the factory method non-static, because static methods aren't inherited.
You can't do this exactly as you have defined the question. The best way to tackle this is really to pull your factory out of the class completely:
public class BankAccount
{
}
public class SavingsAccount : BankAccount
{
}
public static class BankAccountFactory
{
public static T Create<T>() where T : BankAccount, new()
{
return new T();
}
}
Now the Factory has no dependency on the actual type. You can pass any derived class of BankAccount and get it back without doing any extra work or worrying about inheriting your factory method.
If I may, I'd like to expand upon StriplingWarrior. In fact, you can use static for the factory. This following code shows that a and c are the expected object types. The limit is you cannot use the factory on the base class itself.
private void Testit()
{
var a = SavingsAccount.Factory();
var c = CheckingAccount.Factory();
//var b = BankAccount.Factory(); //can't do this
}
public class BankAccount<T> where T : BankAccount<T>, new()
{
public static T Factory()
{
return new T();
}
}
public class SavingsAccount : BankAccount<SavingsAccount>
{
}
public class CheckingAccount : BankAccount<CheckingAccount>
{
}
In order to use inheritance, you need an instance of an object and a member of that object. In this case, for the object we can't use BankAccount/SavingsAccount because then we would already have what we're trying to get. This means we need an actual factory object, which is what most people are talking about when they talk about a factory. So if we pull that out into a Factory and use inheritance...
public class BankAccountFactory { public virtual GetAccount() { return new BankAccount(); } }
public class SavingsAccountFactory : BankAccountFactory { public override GetAccount() { return new SavingsAccount(); } }
But now how do we get an instance of the proper type? We've just pushed our problem one layer deeper.
Instead, what you probably want to do, is use some sort of configuration to determine the type, or pass the type you want into a method.
public BankAccount GetAccount(AccountType type) { /* */ }
or
public BankAccount GetAccount() { /* Access config */ }
For a simple answer to your question: You don't need to use generics or anything like that, you just need your method to not be static...
I try to achieve the following: I have an interace called IAxis that forces my class TheAxis to have certain methods. In addition I want to implement some kind of abstract class based on a parameter. To explain this will write it down in code:
class TheAxis : IAxis
{
public TheAxis(){ }
public void IMoveToPos(int pos) {} //This is forced by the Interface
}
As the instance of this class is called it should be able to choose which methods to include, similar to virtual methods but not overriding existing methods but adding already coded ones from another class. I am looking for something like this:
abstract class GateAxis
{
public void CloseGate() { IMoveToPos(0); }
}
abstract class XAxis
{
public void MoveToStart() { IMoveToPos(100); }
}
TheGateAxis = new Axis() as GateAxis;
Now I want to be able to use TheGateAxis.Closegate(); but NOT TheGateAxis.MoveToStart();
if I call
TheXAxis = new Axis() as XAxis;
I want to be able to use TheXAxis.MoveToStart(); but NOT TheXAxis.CloseGate();
The Methods Given in XAxis or GateAxis don´t need any methods from TheAxis except the onces given by the interface.
Is it possible to do somethign like that? To add Methods to a class depending on a parameter given while instancing the class?
I hope you get what I am trying to do as I do hard to explain.
Best,
Kevin
Well, if you want classes sharing few methods from a base class, and other being separate, you could do
//an interface (optional)
public interface IAxis {
void MoveToPos(int pos);
}
public abstract class AxisBase : IAxis {
public void MoveToPos(int pos) {
//implementation
}
}
//optionally you can do an IGateAxis interface, inheriting (or not) from IAxis
public interface IGateAxis : IAxis {
void CloseGate();
}
//classes inheriting from AxisBase, implementing IGateAxis
public class GateAxis : AxisBase, IGateAxis {
public void CloseGate() {
MoveToPos(0);
}
}
//another interface, not inheriting from IAxis
public interface IXAxis {
void MoveToStart();
}
//another class inheriting from AxisBase
public class XAxis : AxisBase, IXAxis {
public void MoveToStart() {
MoveToPos(100);
}
}
usage
var gateAxis = new GateAxis();
gateAxis.CloseGate();
//and you can do
gateAxis.MoveToPos(250);
var xAxis = new XAxis();
xAxis.MoveToStart();
//and you can do
xAxis.MoveToPos(40);
with the IGateAxis interface
IGateAxis gateAxis = new GateAxis();
gateAxis.CloseGate();
gateAxis.MoveToPos(1);
with the IXAxis interface
IXAxis xAxis = new XAxis();
gateAxis.MoveToStart();
//but you can't do
//gateAxis.MoveToPos(10);
//as IXAxis doesn't know about this method.
// super class
abstract class TheAxis : IAxis {
public TheAxis() { }
public void IMoveToPos(int pos) { } //This is forced by the Interface
}
abstract class GateAxis : TheAxis {
public virtual void CloseGate() { IMoveToPos(0); }
}
abstract class XAxis : TheAxis {
public virtual void MoveToStart() { IMoveToPos(100); }
}
Now if you derive a class from GateAxis it'll only have access to the interface methods and the methods from GateAxis. Same goes for TheAxis.
Dynamically adding methods, and removing them is not something that you can do in "normal" C# . There is no any OOP pattern that can simulate this.
What you can do, is using ExpandoObject to be able to achieve exactly what you're trying to achieve.
Represents an object whose members can be dynamically added and
removed at run time.
By the way I would not encourage of using it as you are in statical type language domain, so may be it's a godd idea to revise your architectiure a little bit and don't jump in dynamic language domain using C#.
I think the best way to solve this is to use interfaces and a single (base) class.
public interface IAxis {
void MoveToPos(int pos);
}
public interface IGateAxis {
void CloseGate();
}
public interface IXAxis {
void MoveToStart();
}
public class TheAxis : IAxis, IGateAxis, IXAxis {
public TheAxis(){ }
void IAxis.MoveToPos(int pos) {}
void IGateAxis.CloseGate() { ((IAxis)this).MoveToPos(0); }
void IXAxis.MoveToStart() { ((IAxis)this).MoveToPos(100); }
}
IGateAxis gateAxis = new ThisAxis();
gateAxis.CloseGate();
IXAxis xAxis = new ThisAxis();
xAxis.MoveToStart();
This way you can specify which methods are available to certain types of axis. Also, you could force the creation of axis through a factory pattern, or even a single static method, just to facilitate the creation of axis.
Assuming you have more than 3 methods, the easiest way that I see is to simply create a proxy that acts as a chain of responsibility:
public class AxisProxy : IAxis
{
public AxisProxy(params IAxis[] implementations) {
this.implementations = implementations;
}
private IAxis[] implementations;
public virtual void CloseGate()
{
foreach (var item in implementations)
{
try { item.CloseGate(); } catch (NotSupportedException) {}
}
throw new NotSupportedException();
}
public virtual void MoveToStart()
{
foreach (var item in implementations)
{
try { item.MoveToStart(); } catch (NotSupportedException) {}
}
throw new NotSupportedException();
}
}
You can create a base implementation of Axis to make sure all default implementations throw the exception. Derived implementations implement specific functionality.
You can then use it by simply calling
IAxis myAxis = new AxisProxy(new GateAxis(), new XAxis());
NOTE: In this case I would seriously consider changing the types to 'bool'; if you call these methods frequently, exception performance will add up... Also, since the NotSupportedException is not going to change, you can keep a per-method list to remove implementations that throw.