I've got the following bit of (simplified) code:
public abstract class BaseClass
{
[Dependency]
public IRequiredService RequiredService { get; set; }
protected string RequiredParameter { get; private set; }
public BaseClass(string requiredParameter)
{
this.RequiredParameter = requiredParameter;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(string requiredParameter) : base(requiredParameter)
{
RequiredService.DoSomething(); //this will fail!
}
}
In other words, I'd like to have access to the Unity-filled RequiredService in the constructor... but that's impossible, since that property hasn't been filled by Unity yet. I COULD add the IRequiredService as a required constructor parameter, but then I'd need to refactor every constructor of every derived class to also include that parameter.
I was wondering if there's a better way.
In short, I'd like to run a bit of code after a class has been constructed and after unity has filled all the class' properties marked with the [Dependency] attribute.
Is there a simple way to do this?
Instead of putting RequiredService.DoSomething(); in the constructor you can put it in a inside a [InjectionMethod] call, this will allow you to reliably know that RequiredService has been populated.
Related
I have an app that uses a set of dll's from a 3rdparty. I am trying to incorporate an updated version of the dll's that have changed some variables and parameters from int to uints. I think I can easily capture base class events in my derived class and re-throw modified events, but I am not sure of an easy way to handle the direct access of the variables in the base class's member class.
The example below shows the original 3rd party implementation. In the latest version, the member variables of ThirdPartyNumberPair are now uint's. I'm looking for a way to intercept the MyNumberPair.x and .y access in my derived container and do the conversion so I don't have to modify SomeMethod - mainly because it is used in many places.
public class ThirdPartyNumberPair
{
public int x{ get; set; };
public int y{ get; set; };
}
public class ThirdPartyContainer
{
public ThirdPartyNumberPair MyNumberPair;
}
public class MyDerivedContainer : ThirdPartyContainer
{
...
}
public class MyClass
{
public MyDerivedContainer myContainer;
public void MyMethod(){
int i = myContainer.MyNumberPair.x;
myContainer.MyNumberPair.y = 3;
}
}
I've tried creating a derived MyThirdPartyNumberPair and hiding the base ThirdPartyNumberPair, but I didn't find any easy way of getting those values to the base ThirdPartyNumberPair member.
I have a NavigationModel class which implements site navigation. Internally there is a private implementation of NavigationNode which I want to be able to declare within the NavigationModel but not outside of it. How would I accomplish this? When I do the following:
public class NavigationModel
{
public List<NavigationNode> NavigationNodes { get; set; }
public NavigationModel()
{
}
private class NavigationNode
{
}
}
The property tells me:
Inconsistent accessibility: property type
'List' is less accessible than
property 'NavigationModel.NavigationNodes'
The error is raised because by declaring NavigationModel as public, you create a public interface that is used to access NavigationModel. Part of this interface are the signatures of the public methods or properties. By that, you'd publish class NavigationNode that is supposed to be private - hence the error.
In order to fix this, you could create a public interface that only contains the parts of NavigationNode that you want to publish. If you do not want to publish anything, the interface is empty. The following sample shows the basic components:
Public interface INavigationNode.
Property of type List<INavigationNode>.
Private class NavigationNode that implements the interface.
public interface INavigationNode
{
// Add parts of NavigationNode that you want to publish
}
public class NavigationModel
{
public List<INavigationNode> NavigationNodes { get; set; }
public NavigationModel()
{
}
private class NavigationNode : INavigationNode
{
}
}
NavigationNode needs to be public for this to work properly. Making it public still keeps the declaration internal to the containing class NavigationModel yet classes outside NavigationModel can reference it.
I read other threads like this but they didn't work for me.
I got two classes:
public class ClassA
{
public string _shouldBeInteger;
public string _shouldBeBool;
public string _shouldBeDateTime;
}
public class ClassB : ClassA
{
public int? shouldBeInteger
{
get { return (_shouldBeInteger != null) ? Convert.ToInt32(Convert.ToDouble(_shouldBeInteger)) : new int?(); }
set { _shouldBeInteger = Convert.ToString(value); }
}
//... same thing with datetime etc.
}
If I now create a new object of ClassB I get
_shouldBeInteger, _shouldBeBool, _shouldBeDateTime;
shouldBeInteger,shouldBeBool,shouldBeDateTime
But I want to hide the _variables to the User.
Setting them private in ClassB will override them, but I need to access them in order to parse there string values.
Update
There is a ClassC filling ClassAs' values, which mainly is the reason why they have to be writeable. There is no way for me to change the way that works, but I'm fully in Control of ClassA and ClassB
ClassC //not changeAble for me
{
//infomagic filling values of ClassA
}
Setting ClassA variables to private won't work, because programmer of ClassA produced it in a strange way.
Solution
Because ClassA needs to be writeable, but not readable to other classes than inheritated, I finally got this:
ClassA
{
public string _shouldBeInteger { protected get; set; }
//and so on
}
which causes ClassB to work with theese properties, without giving them outside.
Intellisense still shows them, but you might consider using:
[EditorBrowsable(EditorBrowsableState.Never)]
to solve that.
Thanks to all.
I think you can solve your problem using:
public class ClassA
{
protected string _shouldBeInteger;
protected string _shouldBeBool;
protected string _shouldBeDateTime;
}
so those variables are accessible to derived classes but not to user.
EDITED after user update:
I don't know if this could be a vali solution for you, but try:
public class ClassB : ClassA
{
public new int? _shouldBeInteger
{
get { return (base._shouldBeInteger != null) ?
Convert.ToInt32(Convert.ToDouble(base._shouldBeInteger)) :
new int?(); }
set { base._shouldBeInteger = Convert.ToString(value); }
}
}
Inheritance can't hide the members as you would think. The new modifier exists to "hide" a base member, but that doesn't play nice when talking to base types.
http://msdn.microsoft.com/en-us/library/435f1dw2.aspx
You can either change the access level of the fields (the preferred way) or you can wrap the class instead of inheriting from it and provide simple pass-through methods to delegate to the wrapped class. This is called the Adapter Pattern:
public class ClassB
{
private ClassA _wrappedClass;
}
Just as an aside, your public fields are following the naming convention commonly used for private fields.
The required access level for derived classes is protected. If the members are used publicly but in the same assembly you can use protected internal. If the members are used publicly by other assemblies... I'd suggest refactoring.
The problem is that you declared the fields public in the base class. In order not to violate the polymorphic nature of inheritance, anything public in the base class must be public in all derived classes as well. If you could change that, you could never be sure that a ClassB could be passed to something expecting a ClassA.
Therefore, as other people have suggested, you probably want the base class fields to be declared protected, which is like private except derived classes can see them.
However if you do need to access them via an actual instance of ClassA, you could declare them private and give them virtual public properties which the derived class can then override. This at least allows the derived class to change their behaviour, but it still can't actually hide them.
If that also doesn't fit, then it's probably worth considering using composition instead of inheritance because the substitution principle is actually getting in your way, and that's an inheritance fundamental.
If you don't have control over ClassA, you'll need to create a wrapper/adapter class like so:
public class ClassB
{
private readonly _classA = new ClassA();
public int? shouldBeInteger
{
get
{
return (this._classA._shouldBeInteger != null)
? Convert.ToInt32(Convert.ToDouble(this._classA._shouldBeInteger))
: new int?();
}
set
{
this._classA._shouldBeInteger = Convert.ToString(value);
}
}
}
public class ClassB
{
private int shouldBeInteger;
public int ShouldBeInteger
{
get { return shouldBeInteger; }
set { shouldBeInteger = value; }
}
}
OR
public class ClassB
{
public int ShouldBeInteger{ get; set; }
}
In both of this case ShouldBeInteger will be accesible outside the class.
In first case there were a private field, which cannot be accesible outside the class,
values to private filed can be set through the public field.
In second case the compiler automatically create a private backing field and do the same
process as above. This is auto implemented property.
Hope this may help you.
I have the following class:
public abstract class TableServiceEntity
{
protected TableServiceEntity();
protected TableServiceEntity(string partitionKey, string rowKey);
.....
.....
}
I inherit from this class as follows:
public class AuditableTableServiceEntity : TableServiceEntity
{
public string CreatedBy { get; set; }
.....
.....
}
I use the class as follows:
public class Note : AuditableTableServiceEntity
{
public Note() { }
public Note(string dsValue, string pk)
: base(pk, Seq.GetNext(dsValue, pk, "Note").ToString("00000")) { }
It fails saying that the class AuditableTableServiceEntity does not have a constructor that
takes two arguments. To fix I tried to add the following methods to AuditableTableServiceEntity. Is this a valid thing to do or is there some other way? Also I notice it requires me to add a constructor that takes zero arguments. Why is that?
public AuditableTableServiceEntity()
: base()
{
}
public AuditableTableServiceEntity(string pk, string rk)
: base(pk, rk)
{
}
Can someone give me advice as to if I'm on the right track or if there is some better way of doing this. Should I declare the methods on AuditableTableServiceEntity as protected and also should I declare that class as abstract?
Can someone give me advice as to if I'm on the right track or if there is some better way of doing this.
This is the correct approach.
Should I declare the methods on AuditableTableServiceEntity as protected and also should I declare that class as abstract?
It depends. Should the user be able to directly construct an instance of an AuditableTableServiceEntity? If so, then the constructors should be public, and the class should not be abstract.
If, however, it doesn't make sense, and the user should always construct a Note or other similar class, then protected constructors and an abstract class is appropriate.
I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
public BaseClass(int someValue) {}
//...more code, not important here
}
and, my proxy resembles:
public BaseClassProxy : BaseClass
{
public BaseClassProxy(bool fakeOut){}
}
Without the "fakeOut" constructor, the base constructor is expected to be called. However, with it, I expected it to not be called. Either way, I either need a way to not call any base class constructors, or some other way to effectively proxy this (evil) class.
There is a way to create an object without calling any instance constructors.
Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution.
This is how you do it:
FormatterServices.GetUninitializedObject(typeof(MyClass));
Call it in place of the object's constructor. It will create and return you an instance without calling any constructors or field initializers.
When you deserialize an object in WCF, it uses this method to create the object. When this happens, constructors and even field initializers are not run.
If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.
At least 1 ctor has to be called. The only way around it I see is containment. Have the class inside or referencing the other class.
I don't believe you can get around calling the constructor. But you could do something like this:
public class BaseClass : SomeOtherBase
{
public BaseClass() {}
protected virtual void Setup()
{
}
}
public BaseClassProxy : BaseClass
{
bool _fakeOut;
protected BaseClassProxy(bool fakeOut)
{
_fakeOut = fakeOut;
Setup();
}
public override void Setup()
{
if(_fakeOut)
{
base.Setup();
}
//Your other constructor code
}
}
If what you want is to not call either of the two base class constructors, this cannot be done.
C# class constructors must call base class constructors. If you don't call one explicitly, base( ) is implied. In your example, if you do not specify which base class constructor to call, it is the same as:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base() { }
}
If you prefer to use the other base class constructor, you can use:
public BaseClassProxy : BaseClass
{
public BaseClassProxy() : base(someIntValue) { }
}
Either way, one of the two will be called, explicitly or implicitly.
When you create a BaseClassProxy object it NEEDS to create a instance of it's base class, so you need to call the base class constructor, what you can doo is choose wich one to call, like:
public BaseClassProxy (bool fakeOut) : base (10) {}
To call the second constructor instead of the first one
I am affraid that not base calling constructor isn't option.
I ended up doing something like this:
public class BaseClassProxy : BaseClass
{
public BaseClass BaseClass { get; private set; }
public virtual int MethodINeedToOverride(){}
public virtual string PropertyINeedToOverride() { get; protected set; }
}
This got me around some of the bad practices of the base class.
constructors are public by nature. do not use a constructor and use another for construction and make it private.so you would create an instance with no paramtersand call that function for constructing your object instance.
All right, here is an ugly solution to the problem of one class inheriting the constructors of another class that I didn't want to allow some of them to work. I was hoping to avoid using this in my class but here it is:
Here is my class constructor:
public MyClass();
{
throw new Exception("Error: Must call constructor with parameters.");
}
OK now you were warned that it was ugly. No complaints please!
I wanted to force at least the minimal parameters from my main constructor without it allowing the inherited base constructor with no parameters.
I also believe that if you create a constructor and do not put the : base() after it that it will not call the base class constructor. And if you create constructors for all of the ones in the base class and provide the same exact parameters for them in the main class, that it will not pass through. But this can be tedious if you have a lot of constructors in the base class!
It is possible to create an object without calling the parameterless constructor (see answer above). But I use code like this to create a base class and an inherited class, in which I can choose whether to execute the base class's init.
public class MyClass_Base
{
public MyClass_Base()
{
/// Don't call the InitClass() when the object is inherited
/// !!! CAUTION: The inherited constructor must call InitClass() itself when init is needed !!!
if (this.GetType().IsSubclassOf(typeof(MyClass_Base)) == false)
{
this.InitClass();
}
}
protected void InitClass()
{
// The init stuff
}
}
public class MyClass : MyClass_Base
{
public MyClass(bool callBaseClassInit)
{
if(callBaseClassInit == true)
base.InitClass();
}
}
Here is my solution to the problem
using System;
public class Program
{
public static void Main()
{
Console.WriteLine(new Child().Test);
}
public class Child : Parent {
public Child() : base(false) {
//No Parent Constructor called
}
}
public class Parent {
public int Test {get;set;}
public Parent()
{
Test = 5;
}
public Parent(bool NoBase){
//Don't do anything
}
}
}
A simple elegant solution. You can change it according to your need.
Another simple solution from me:
class parent
{
public parent()
{
//code for all children
if (this.GetType() == typeof(child1))
{
//code only for objects of class "child1"
}
else
{
//code for objects of other child classes
}
}
}
class child1 : parent
{
public child1()
{}
}
// class child2: parent ... child3 : parent ... e.t.c