Ninject binding based on object's property? Convention or contextual binding? - c#

I have an interface:
public interface IInterface
{
string Get(obj o);
}
and I have the 2 classes:
public class C1 : IInterface
{
string Get(obj o);
}
public class C2 : IInterface
{
string Get(obj o);
}
I'd like to send in o and then have Ninject determine which interface it is based on the property of o. Obj being something like:
public class obj
{
public string Name {get;set;}
public int Id {get;set;}
}
I'd like something that's like:
Bind<IInterface>().To<C1>.When(obj.Name == "C1");
Bind<IInterface>().To<C2>.When(obj.Name == "C2");
but I haven't worked with Ninject before. Any ideas?

I've been somewhat liberal with the interpretation of your question, because i think you've skipped some "thinking steps" and necessary information.
However, what I recommend is doing it like this:
public interface INamed
{
string Name { get; }
}
public interface IFactory
{
IInterface Create(INamed obj);
}
public class Factory : IFactory
{
private readonly IResolutionRoot resolutionRoot;
public Factory(IResolutionRoot resolutionRoot)
{
this.resolutionRoot = resolutionRoot;
}
public IInterface Create(INamed obj)
{
return this.resolutionRoot.Get<IInterface>(obj.Name);
}
}
Alternative: you could also use the ninject factory extension. Sadly enough it does not support named bindings by default, but you can customize it do so like documented here.
However to be perfectly frank i would rather go for manually implementing the factory, because it is more easily understandable. If i would be customizing the factory - which i have done - i would consider adding support for attributes (which specify how to handle a factory method parameter) instead of having to configure each .ToFactory() binding how it will interpret parameters.

Related

Polymorphic Abstract class with a lot of DI paramters

I'm constantly running into the problem of having an abstract class that does all the heavy lifting and then I have a lot of polymorphic classes that customize the abstract to a specific need. The abstract generally needs a lot of parameters, so they all have to be passed from all polymorphic classes
public class FooComplex : AbstractFoo {
public FooComplex(IBarAwesome awesome, IBarCool cool, ...) : base(IBarAwesome awesome, IBarCool cool, ...) { }
...a lot of overriding abstracts
}
public class FooSimple : AbstractFoo
{
public FooSimple(IBarAwesome awesome, IBarCool cool, ...) : base(IBarAwesome awesome, IBarCool cool, ...) { }
...little bit of overriding abstracts
}
public class AbstractFoo
{
public AbstractFoo(IBarAwesome awesome, IBarCool cool, ...)
...heavy lifting
}
Is there anything I can do to not pass all these things, but be able to unit test them? I've always been taught that doing
var awesome = container.Resolve<IBarAwesome>();
In like say the constructor is bad practice.
The reason I would like to find a solution to this, is it makes it harder and hard to pass anything new into the abstract class as I have to copy and pass the same parameters into many polymorphic subclasses.
I believe this is similar to what #C.Evenhuis mentioned in the comments by abstracting your constructor parameters into a common interface so they can be passed as single constructor parameter as well as being easily tested.
Concrete Classes:
public class FooComplex : AbstractFoo
{
public FooComplex(ComplexParam complexParam) : base(complexParam)
{}
}
public class FooSimple : AbstractFoo
{
public FooSimple(SimpleParam simpleParam) : base(simpleParam)
{}
}
Single Generic Concrete Class (Optional)
With this class, you could pass any type into the constructor which inherits IParams and potentially remove the need for FooComplex and FooSimple.
public class Foo<T> : AbstractFoo where T : IParam
{
public Foo(T param) : base(param)
{ }
}
Base Abstract Class:
public abstract class AbstractFoo
{
protected AbstractFoo(IParam parameter) { }
}
Interfaces:
public interface IBarCool : IBar
{}
public interface IBarAwesome : IBar
{}
public interface IBar
{}
public interface IParam
{
IEnumerable<IBar> Param { get; }
}
Reusable Concrete Parameters:
I personally don't like this method below because of the repetition but I suppose if each of the classes have their own separate implementation then it's okay. Another option would be to just have a class called ParameterHolder and two instances of the class named appropriately e.g. var complex = new ParameterHolder() and pass to the Generic Foo<T>.
public class ComplexParam : IParam
{
public IEnumerable<IBar> Param { get; }
public ComplexParam(IEnumerable<IBar> complexParam)
{
Param = complexParam;
}
}
public class SimpleParam : IParam
{
public IEnumerable<IBar> Param { get; }
public SimpleParam(IEnumerable<IBar> simpleParam)
{
Param = simpleParam;
}
}
All that needs to happen is:
public interface IAbstractParams
{
IBarAwesome awesome { get; }
IBarCool cool { get; }
...
}
public class FooComplex : AbstractFoo
{
public FooComplex(IAbstractParams params) : base(params) { }
...a lot of overriding abstracts
}
public class FooSimple : AbstractFoo
{
public FooSimple(IAbstractParams params) : base(params) { }
...little bit of overriding abstracts
}
public class AbstractFoo
{
protected readonly IBarAwesome _awesome;
protected readonly IBarCool _cool;
public AbstractFoo(IAbstractParams params)
{
_awesome = params.awesome;
_cool = params.cool;
}
...heavy lifting
}
then you need to add the nuget package Autofac.Extras.AggregateService and add this line to your builder:
builder.RegisterAggregateService<IAbstractParams>();
Thank you to #Travis Illig and #C.Evenhuis for helping me come up with this solution.
For more complex solutions to this same problem please look at #Kitson88

Declare a generic type as property of an interface?

I've a Generic type, which is used to give some meta data on an object to persist:
public class PersistedElementDefinition<T> where T: IPersistedObject{
List<PersistedPropertyDefinition<T>> PropertiesToPersist {get;set;}
}
public class PersistedPropertyDefinition<T> where T: IPersistedObject{
public Func<T, object> PropertyGetter{get;set;}
public Action<T, object> PropertySetter {get;set;}
}
and I've my IPersistedObject which can give his definition
public interface IPersistedObject{
PersistedElementDefinition<TypeOfTheImplementingType> Definition {get;}
}
The idea is that if I implement IPersistedObject I should implement it like this:
public class MyPersistedObject:IPersistedObject{
PersistedElementDefinition<MyPersistedObject> Definition{get;}
}
When I persist my class have the following thing:
I can't do the following:
public interface IPersistedObject<T>{
PersistedElementDefinition<T> Definition {get;}
}
because:
It would allow to have a MyPersistedObject<SomeOtherObject
At some point I receive an object, and I should be able to see if it implements the IPersistedObject and do some custom action with it.
For the 2, here is an example of what kind of issue I'm facing if I've a Generic interface:
public void Persist<T>(T objectToPersist)where T:IPersistedObject{
...
foreach(PersistedPropertyDefinition<T> property in objectToPersist.PropertiesToPersist){
object objectToSerialize = property.ObjectGetter(objectToPersist);
if(objectToSerialize is IPersistedObject<___Don't know how to put something generic here___>){
Persist((IPersistedObject<___Don't know how to put something generic here___>)objectToSerialize);
}
}
...
}
Is there a possibility in c# to declare an interface with a generic property of the implementing type?
You can use the curiously recurring template pattern to lock this down a bit further. It isn't bulletproof, but assuming you're not a masochist, and you don't mind the fact that it is theoretically possible to create nonsensical implementations of the interface that violate the invariants you are trying to guarantee, you can do this:
public interface IPersistedObject<T> where T : IPersistedObject<T>
{
PersistedElementDefinition<T> Definition {get;}
}
public class PersistedElementDefinition<T> where T: IPersistedObject<T>
{
...
}
public class MyPersistedObject : IPersistedObject<MyPersistedObject>
{
// Here, you are forced to implement a PersistedElementDefinition<MyPersistedObject>,
// which presumably is the reason behind this whole song and dance
PersistedDefinition<MyPersistedObject> Definition { get; }
}
The problem with this, as you noticed at the outset, is that you could simply define public class MyPersistedObject : IPersistedObject<MyOtherPersistedObject>, and end up breaking the contract you are trying to cobble together, which in plain words is the following:
A persisted object must have a gettable definition that is a persisted element definition of its own type
The C# type system is simply not equipped to handle this elegantly. My advice is to get out early, change to object or dynamic where possible and learn to live with the loss of certain compile time guarantees.
Assuming you're willing to sacrifice some compile time safety, you could do things like so:
class Program
{
static void Main(string[] args)
{
var mpo = new MyPersistedObject();
var ptp = mpo.Definition.PropertiesToPersist;
}
}
public class PersistedElementDefinition<T> where T : IPersistedObject
{
private readonly List<PersistedPropertyDefinition<T>> _propsToPersist = new List<PersistedPropertyDefinition<T>>();
public List<PersistedPropertyDefinition<T>> PropertiesToPersist
{
get { return _propsToPersist; }
}
}
public class PersistedPropertyDefinition<T> where T : IPersistedObject
{
public Func<T, object> PropertyGetter { get; set; }
public Action<T, object> PropertySetter { get; set; }
}
public interface IPersistedObject
{
dynamic Definition { get; }
}
public class MyPersistedObject : IPersistedObject
{
private readonly PersistedElementDefinition<MyPersistedObject> _definition = new PersistedElementDefinition<MyPersistedObject>();
public dynamic Definition { get { return _definition; } }
}

Defining interface dependency that implements generics

This will be generics 101 for many but below is sample code so I can understand better.
public interface IRecordedItemsProcessor<T>
{
ObservableCollection<RecordedItem> Load(string name);
void Save();
RecordedItem Parse(T itemToParse);
}
public class FileLoadingProcessor : IRecordedItemsProcessor<string>
{
public ObservableCollection<RecordedItem> Load(string name)
{
}
public void Save()
{
}
public RecordedItem Parse(string itemToParse)
{
}
}
public class MyClass
{
public MyClass(IRecordedItemsProcessor<T> processor)
{
}
}
The issue is that MyClass needs a dependency on IRecordedItemsProcessor<T> but will not compile as it does not know what T is. How can this be resolved? Making MyClass implement a seems odd as all it needs to do is call Load/Save
Thanks
First solution is the most simple one: lift generic declaration to class level, like
public class MyClass<T>
{
public MyClass(IRecordedItemsProcessor<T> processor)
{
}
}
Then you could instantiate MyClass as following:
var myClass = new MyClass<string>(new FileLoadingProcessor());
Console.WriteLine (myClass);
Second solution is a removing generic input from constructor and inferring types. Then you don't need to specify generic exactly from call. Class declaration will look like:
public class MyClass
{
public void Process<T>(IRecordedItemsProcessor<T> processor)
{
}
}
And then you can call simply
var my = new MyClass();
my.Process(new FileLoadingProcessor());
The Idea is that you always need to specify class-level generics explicitly, but method level generics can be inferred by the compiler.
Third solutions is to encapsulate creation mechanisms inside MyClassFactory. This is quite flexible, but it might seem a little bit complicated, because descendants of IRecordedItemsProcessor<T> don't define generic at class level, so we should go to implemented interfaces and grab there generic types. And only then we can construct Generic MyClass. Listing is given below:
public class MyClassFactory
{
public MyClass<T> MakeMyClassFor<T>(IRecordedItemsProcessor<T> processor)
{
var processorGenericType = processor.GetType()
.GetInterfaces()
.Single(intr=>intr.Name == "IRecordedItemsProcessor`1")
.GetGenericArguments()[0];
var myClassType = typeof(MyClass<>).MakeGenericType(processorGenericType);
return Activator.CreateInstance(myClassType, processor) as MyClass<T>;
}
}
Now you can create MyClass very simply
var myClassFactory = new MyClassFactory();
var res = myClassFactory.MakeMyClassFor(new FileLoadingProcessor());
Console.WriteLine (res);
All of these three approaches have their pros and cons. Consider taking into account the context, in which you are going to use them.
You could do the following:
Create a new interface IRecordedItemsProcessor (non-generic)
Move Load and Save to this IRecordedItemsProcessor
Make IRecordedItemsProcessor<T> inherit from this IRecordedItemsProcessor
Make MyClass expect IRecordedItemsProcessor in its constructor
This makes it clear that MyClass doesn't care what type the processor might be able to parse, or even that it can parse things at all - it only knows that it can save and load.
You could inherit from a non-generic marker interface, this removes the need to know about T in your class:
public interface IRecordedItemsProcessor
{
}
public interface IRecordedItemsProcessor<T> : IRecordedItemsProcessor
{
ObservableCollection<RecordedItem> Load(string name);
void Save();
RecordedItem Parse(T itemToParse);
}
And then you can use any IRecordedItemsProcessor like:
public class MyClass
{
public MyClass(IRecordedItemsProcessor processor)
{
}
}
The generic type, as written, is being declared on the MyClass constructor which means the generic type must be defined at the MyClass level:
public class MyClass<T>
{
public MyClass(IRecordedItemsProcessor<T> processor)
{
}
}
However, if the generic type was declared at a method level, it would only have to be defined at the method level:
public class MyClass
{
public void MyMethod<T>( IRecordedItemsProcessor<T> processor )
{
}
}
EDIT
Based on your comment:
I want a class that can call the Load/Save methods but not be worried
that T is.
Then you'll need 2 interfaces: 1 for the load/save and then one with the parsing. In this case, you could use inheritance:
public interface IRecordedItems
{
ObservableCollection<RecordedItem> Load( string name );
void Save();
}
public interface IRecordedItemsProcessor<T> : IRecordedItems
{
RecordedItem Parse( T itemToParse );
}
public class MyClass : IRecordedItems
{
#region Implementation of IRecordedItems
public ObservableCollection<RecordedItem> Load( string name )
{
throw new NotImplementedException();
}
public void Save()
{
throw new NotImplementedException();
}
#endregion
}
EDIT 2
Based on your gist example, the type dependency could be moved off of the interface and directly into the interface method:
public class RecordedItem {}
public interface IRecordedItemsProcessor
{
ObservableCollection<RecordedItem> Load( string name );
void Save();
RecordedItem Parse<T>( T itemToParse );
}
public class MyClass
{
private readonly IRecordedItemsProcessor _processor;
public MyClass( IRecordedItemsProcessor processor )
{
_processor = processor;
processor.Parse<string>( "foo" );
processor.Parse<int>( 10 );
processor.Parse<RecordedItem>( new RecordedItem() );
}
}

Define a method in interface which takes n parameters

I am trying to define an interface and classes which implement the interface as below. The method defined in the interface accepts a string as argument where myClass2 implementation of the method Execute takes 2 arguments which doesn't follow the interface definition.
That's the problem. How could I define a method within an interface which takes n number of parameters of various type?
Please advice. Thanks.
public interface MyInterface
{
void Execute(string a);
}
public class myClass1 : MyInterface
{
public void Execute(string a)
{
Console.WriteLine(a);
}
}
public class myClass2 : MyInterface
{
public void Execute(string a, int b)
{
Console.WriteLine(a);
Console.WriteLine(b.ToString());
}
}
EDIT: I am thinking of another approach. I appreciate if someone could tell me if this will be a better design.
public interface IParameter
{
Type ParameterType { get; set; }
string Name { get; set; }
object Value { get; set; }
}
public interface MyInterface
{
void Execute(Recordset recordSet, List<IParameter> listParams);
}
public class MyClass : MyInterface
{
public void Execute(Recordset recordSet, List<IParameter> listParams)
{
}
}
I am passing a list of IParameter which holds all the required parameters which need to be sent.
How would the caller know how to call the method, if the interface didn't fix the parameter types?
The closest you can can would be:
public interface MyInterface
{
void Execute(params object[] args);
}
Implementations of the interface would have to then deal with any number of arguments being passed in though - you couldn't have an implementation which only handled a single int parameter, although it could of course throw an exception if args contains anything other than a single int value.
EDIT: Just to be clear, this would rarely be a good design. In some very weakly typed scenarios it may be appropriate, but otherwise, usually it would be worth trying to find something better.
If you can give more information about what you're trying to do, we may be able to help you more.
You can't do this for good reason. Different implementations of interfaces are meant to be used interchangeably. Your proposed design violates this principle. If you want help solving the conflict I think you need to explain what led you to this design.
So you're defining your interface as
public interface MyInterface
{
void Execute(string a);
}
and attempting to implement it as
public void Execute(string a, int b)
{
...
}
That won't work - you're declaring one interface, and attempting to define something else.
What might work (and I can't tell based on your post thus far) is explicit interface implementation - that is, your concrete object could expose an Execute(string, int) method and explicitly implement your interface method. Something like
public class myClass2 : MyInterface
{
public void Execute(string a, int b)
{
...
}
void MyInterface.Execute(string a)
{
...
}
}
That said, I'd strongly advise that you rethink this design. The entire point of interfaces is that they expose a common programmatic surface to the rest of your code - breaking that contract stinks to high heaven, in terms of code-smells.
In addition to #Jon answer: considering that you are implementing an Interface, so you are architect, just don't use an interface but simple base class with overloaded virtual functions and in every concrete class ocerride it in a way you prefer.
EDIT:
I mean something like this: instead of using interface declare base class, a pseudocode!
public class MyCoolBase // a base CLASS and not interface
{
public virtual void Execute(string a)
{
//empty, or NotImplementedException, base on design decision
}
public virtual void Execute(double b)
{
//empty, or NotImplementedException, base on design decision
}
public virtual void Execute(int a, int b)
{
//empty, or NotImplementedException, base on design decision
}
}
public class MyCoolChildOne : MyCoolBase
{
public override void Execute(string a)
{
//concrete implementation
}
}
public class MyCoolChildTwo : MyCoolBase
{
public override void Execute(int a, int b)
{
//concrete implementation
}
}
and so on...
Bad: When you do something like this in the code
MyCoolBase myCoolBase = new MyCoolChildOne ();
myCoolBase...?(); // should be really sure which function you're going to call on this line
Good: You have strong types management, and no more object[] arrays, or multiple inheritance from more then one interface which you must override, instead in this case you cam even avoid it, even if I think it's not so good idea.
By the way, like geeks here said, I don't think your architecture is very reliable, there should be some other solution around for you. We just try to find out the best choice looking on code and question, but real problem can know only you.
Hope this helps.
Regards.
You can do that with weakly typed approach. E.g., you could define an interface that takes objects array:
public intrface MyInterface
{
void Execute(params object[] args);
}
And than you can call any of your concrete class with any arguments:
myClass.Execute("string", 1);
But in this case you violate the main purpose of interfaces, inheritance and compile-time checks.
Another way to implement this is to achieve this is to encapsulate all parameters in additional class hierarchy:
class CommandData
{
public string StringData {get; set;}
}
class ExtendedCommandData : CommandData
{
public int I {get;set;}
}
interface IMyInterface
{
public void Execute(CommandData commandData);
}
class MyClass1 : IMyInterface
{
public void Execute(CommandData commandData);
}
class MyClass2 : IMyInterface
{
// Lets impelment this interface explicitely
void IMyInterface.Execute(CommandData commandData)
{
}
void Execute(ExtendedCommandData extendedData)
{
// now we can access to string and int parameter
}
}
For what it's worth, this might be a great use case for generics.
You define the minimum required parameters as properties of an interface, then inherit where more parameters are required.
Looks quite silly when you're only using 1 parameter in the base interface, but of course this concept could be expanded to more complex types.
public interface MyInterface<T> where T : ParamA
{
void Execute(T paramA);
}
public interface ParamA
{
string ParameterA { get; }
}
public class myClass1 : MyInterface<myClass1.myParamA>
{
public class myParamA : ParamA
{
public string ParameterA { get; set; }
}
public void Execute(myParamA a)
{
Console.WriteLine(a.ParameterA);
}
}
public class myClass2 : MyInterface<myClass2.myParamsAb>
{
public class myParamsAb : ParamA
{
public string ParameterA { get; set; }
public int ParameterB { get; set; }
}
public void Execute(myParamsAb ab)
{
Console.WriteLine(ab.ParameterA);
Console.WriteLine(ab.ParameterB.ToString());
}
}

Creating read-only versions of classes in a complex object structure

In my current project I need to be able to have both editable and read-only versions of classes. So that when the classes are displayed in a List or PropertGrid the user is not able to edit objects they should not be allowed to.
To do this I'm following the design pattern shown in the diagram below. I start with a read-only interface (IWidget), and then create an edtiable class which implements this interface (Widget). Next I create a read-only class (ReadOnlyWidget) which simply wraps the mutable class and also implements the read only interface.
I'm following this pattern for a number of different unrelated types. But now I want to add a search function to my program, which can generate results that include any variety of types including both mutable and immutable versions. So now I want to add another set of interfaces (IItem, IMutableItem) that define properties which apply to all types. So IItem defines a set of generic immutable properties, and IMutableItem defines the same properties but editable. In the end a search will return a collection of IItems, which can then later be cast to more specific types if needed.
Yet, I'm not sure if I'm setting up the relationships to IMutable and IItem correctly. Right now I have each of the interfaces (IWidget, IDooHickey) inheriting from IItem, and then the mutable classes (Widget, DooHickey) in addition also implement IMutableItem.
Alternatively, I was also thinking I could then set IMutableItem to inherit from IItem, which would hide its read-only properties with new properties that have both get and set accessors. Then the mutable classes would implement IMutableItem, and the read-only classes would implement IItem.
I'd appreciate any suggestions or criticisms regarding any of this.
Class Diagram
Code
public interface IItem
{
string ItemName { get; }
}
public interface IMutableItem
{
string ItemName { get; set; }
}
public interface IWidget:IItem
{
void Wiggle();
}
public abstract class Widget : IWidget, IMutableItem
{
public string ItemName
{
get;
set;
}
public void Wiggle()
{
//wiggle a little
}
}
public class ReadOnlyWidget : IWidget
{
private Widget _widget;
public ReadOnlyWidget(Widget widget)
{
this._widget = widget;
}
public void Wiggle()
{
_widget.Wiggle();
}
public string ItemName
{
get {return _widget.ItemName; }
}
}
public interface IDoohickey:IItem
{
void DoSomthing();
}
public abstract class Doohickey : IDoohickey, IMutableItem
{
public void DoSomthing()
{
//work it, work it
}
public string ItemName
{
get;
set;
}
}
public class ReadOnlyDoohickey : IDoohickey
{
private Doohickey _doohicky;
public ReadOnlyDoohickey(Doohickey doohicky)
{
this._doohicky = doohicky;
}
public string ItemName
{
get { return _doohicky.ItemName; }
}
public void DoSomthing()
{
this._doohicky.DoSomthing();
}
}
Is it OK to create another object when you need a readonly copy? If so then you can use the technique in the included code. If not, I think a wrapper is probably your best bet when it comes to this.
internal class Test
{
private int _id;
public virtual int ID
{
get
{
return _id;
}
set
{
if (ReadOnly)
{
throw new InvalidOperationException("Cannot set properties on a readonly instance.");
}
}
}
private string _name;
public virtual string Name
{
get
{
return _name;
}
set
{
if (ReadOnly)
{
throw new InvalidOperationException("Cannot set properties on a readonly instance.");
}
}
}
public bool ReadOnly { get; private set; }
public Test(int id = -1, string name = null)
: this(id, name, false)
{ }
private Test(int id, string name, bool readOnly)
{
ID = id;
Name = name;
ReadOnly = readOnly;
}
public Test AsReadOnly()
{
return new Test(ID, Name, true);
}
}
I would suggest that for each main class or interface, there be three defined classes: a "readable" class, a "changeable" class, and an "immutable" class. Only the "changeable" or "immutable" classes should exist as concrete types; they should both derive from an abstract "readable" class. Code which wants to store an object secure in the knowledge that it never changes should store the "immutable" class; code that wants to edit an object should use the "changeable" class. Code which isn't going to write to something but doesn't care if it holds the same value forever can accept objects of the "readable" base type.
The readable version should include public abstract methods AsChangeable(), AsImmutable(), public virtual method AsNewChangeable(), and protected virtual method AsNewImmutable(). The "changeable" classes should define AsChangeable() to return this, and AsImmutable to return AsNewImmutable(). The "immutable" classes should define AsChangeable() to return AsNewChangeable() and AsImmutable() to return this.
The biggest difficulty with all this is that inheritance doesn't work terribly well if one tries to use class types rather than interfaces. For example, if one would like to have an EnhancedCustomer class which inherits from BasicCustomer, then ImmutableEnhancedCustomer should inherit from both ImmutableBasicCustomer and ReadableEnhancedCustomer, but .net doesn't allow such dual inheritance. One could use an interface IImmutableEnhancedCustomer rather than a class, but some people would consider an 'immutable interace' to be a bit of a smell since there's no way a module that defines an interface in such a way that outsiders can use it without also allowing outsiders to define their own implementations.
Abandon hope all ye who enter here!!!
I suspect that in the long run your code is going to be very confusing. Your class diagram suggests that all properties are editable (or not) in a given object. Or are your (I'm)mutable interfaces introducing new properties that are all immutable or not, separate from the "core"/inheriting class?
Either way I think you're going to end up with playing games with property name variations and/or hiding inherited properties
Marker Interfaces Perhaps?
Consider making all properties in your classes mutable. Then implement IMutable (I don't like the name IItem) and IImutable as a marker interfaces. That is, there is literally nothing defined in the interface body. But it allows client code to handle the objects as a IImutable reference, for example.
This implies that either (a) your client code plays nice and respects it's mutability, or (b) all your objects are wrapped by a "controller" class that enforces the given object's mutability.
Could be too late :-), but the cause "The keyword 'new' is required on property because it hides property ..." is a bug in Resharper, no problem with the compiler. See the example below:
public interface IEntityReadOnly
{
int Prop { get; }
}
public interface IEntity : IEntityReadOnly
{
int Prop { set; }
}
public class Entity : IEntity
{
public int Prop { get; set; }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var entity = new Entity();
(entity as IEntity).Prop = 2;
Assert.AreEqual(2, (entity as IEntityReadOnly).Prop);
}
}
Same for the case without interfaces. The only limitation, you can't use auto-properties
public class User
{
public User(string userName)
{
this.userName = userName;
}
protected string userName;
public string UserName { get { return userName; } }
}
public class UserUpdatable : User
{
public UserUpdatable()
: base(null)
{
}
public string UserName { set { userName = value; } }
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var user = new UserUpdatable {UserName = "George"};
Assert.AreEqual("George", (user as User).UserName);
}
}

Categories