C# Singleton that implements different interfaces based on environment - c#

What is the best approach to choosing between multiple interfaces based on the environment? My code is running in multiple environments. If its running on environment1 then the Singleton needs to implement IClass1.And on environment2 then it needs to implement IClass2. These two Interfaces share the same base adapter called IClassBase. My current approach only lets my singleton use the IClassBase's methods.
public interface IClassBase
{
public int BaseMethod();
}
public interface IClass1: IClassBase
{
void IClassMethod();
}
public interface IClass2: IClassBase
{
void IClass2Method();
}
public class Singleton: IClassBase
{
private static readonly Lazy<IClassBase> _instance
= new Lazy<IClassBase>(() => IsEnvironment1() ? new IClass1(): new IClass2());
public static IClassBase Instance { get { return _instance.Value; } }
public static bool IsEnvironment1()
{
// some logic to determine which environment
return true;
}
public int BaseMethod()
{
return 1;
}
}

Related

How can I access private members from other classes?

I'm not that new to C# but don't have as much experience as in Java.
As you know, in Java, we can access all the private members from outer classes.
So I tried the same thing in C# because I had some fields and methods needed to be accessed from only inside my plugin library and didn't want it to be shown to users. A simple example can be like this.
public static class StaticClass {
public class InstanceClass {
private int oldValue;
public int Value;
}
public static void Backup(InstanceClass ic) {
ic.oldValue = ic.Value;
}
public static void Restore(InstanceClass ic) {
ic.Value = ic.oldValue;
}
}
If I make the field oldValue public, then it'll be mess and look dirty when end users use the plugin. It doesn't have to be an Inner class or in a some specific form. I just want to know if there is any way to control or access private members of an instance from other static classes in the same assembly only by me.
For allowing access only within assembly use internal modifier.
public class InstanceClass {
internal int oldValue;
public int Value;
}
This is not possible in C#. The container class has no special access over the nested class.
You can access private members of the container from the nested class, but not vice versa. The pattern you're trying to use simply isn't used in C# - it's a violation of member accessibility. There are some hacks to force the Java pattern on C# (using reflection or abusing interfaces), but they are just that - hacks.
The "cleanest" approach might look something like this:
public static class StaticClass
{
private interface IInstanceClassInternal
{
int OldValue { get; set; }
}
public sealed class InstanceClass : IInstanceClassInternal
{
int IInstanceClassInternal.OldValue { get; set; }
public int Value;
}
public static void Backup(InstanceClass ic)
{
((IInstanceClassInternal)ic).OldValue = ic.Value;
}
public static void Restore(InstanceClass ic)
{
ic.Value = ((IInstanceClassInternal)ic).OldValue;
}
}
It's obvious that you're trying to write Java in C# - the patterns, the coding style... That's probably a bad idea. Those static methods should probably be extension methods. The "hidden functionality in an object" doesn't quite sit with C#'s notion of OOP - your parent shouldn't have free access to your guts, it should only really have the same public interface everyone else has. After all, that's the whole point of LSP - such tight coupling is quite tricky for any extensibility. Why separate StaticClass from InstanceClass in the first place, if you want StaticClass to mess with InstanceClasses privates? Just make Backup and Restore public members of InstanceClass - or even a part of an interface (perhaps even through explicit implementation, if you want to "hide" it from users of InstanceClass).
You can use the internal access modifier, see https://msdn.microsoft.com/en-us/library/ms173121.aspx
Internal is only visible from inside the assembly
Example: https://dotnetfiddle.net/FNavfE
Have you tried to make it "internal"? It will be available in same dll but not external dll.
public class InstanceClass {
internal int oldValue;
public int Value;
}
Technically, you can use Reflection (if you insist on private field and a static class methods):
using System.Reflection;
...
public static void Backup(InstanceClass ic) {
if (null == ic)
throw new ArgumentNullException("ic");
ic.GetType()
.GetField("oldValue", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(ic, ic.Value);
}
public static void Restore(InstanceClass ic) {
if (null == ic)
throw new ArgumentNullException("ic");
ic.Value = (int) (ic.GetType()
.GetField("oldValue", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(ic));
}
however, a much better approach is to change access modifier from private to internal:
public class InstanceClass {
internal int oldValue;
public int Value;
}
Even better solution is to move both Backup and Restore methods into InstanceClass:
public class InstanceClass {
private int oldValue;
public int Value;
public void Backup() {
oldValue = Value;
}
public void Restore() {
Value = oldValue;
}
}
This field oldValue is an implementation detail of both StaticClass and InstanceClass. Lets make InstanceClass an implementation detail of StaticClass and export an interface StaticClass.IInstance to external clients:
public static class StaticClass {
public interface IInstance {
int Value { get; set; }
}
private class InstanceClass: IInstance {
public int oldValue;
public Value { get; set; }
}
// Static class becomes responsible for handing out `IInstance` objects
public static IInstance GetInstance() {
return new InstanceClass();
}
public static void Backup(IInstance i) {
if (i is InstanceClass ic) {
ic.oldValue = ic.Value;
}
else {
throw new InvallidOperationException("Can only Backup IInstance objects that were created by GetInstance");
}
}
public static void Restore(IInstance i) {
if (I is InstanceClass ic)
{
ic.Value = ic.oldValue;
}
else {
throw new InvallidOperationException("Can only Restore IInstance objects that were created by GetInstance");
}
}
This solution is similar to the one Luaan proposes. But instead of using an interface to export private data, it uses an interface to limit the publicly available data; to my opinion this is a cleaner design with less surprises.
It does change Value from a field to a property; so when you really need a field, this pattern does not work.
The static class in the example of OP makes it a bit awkward and having better solutions, but imagine this in a regular class, perhaps in a repository. Working on a repository, where observers should be notified when properties of items in the repository are set and not wanting the items to contain a reference to the repository or to the repositories observers, led me to searching for "method only accessible to container class?" which led me to this question.
I intend to solve it as follows:
public class Repo
{
public interface IItem
{
int Id { get; }
string MyProperty { get; }
}
private class Item
{
public int Id { get; }
public string MyProperty { get; private set; }
public bool TrySetMyProperty(string newValue)
{
if (!Equals(MyProperty, newValue) &&
IsPreconditionValid())
{
MyProperty = newValue;
return true;
}
else
{
return false;
}
IsPreconditionValid() => true;
}
}
public event EventHandler<EventArgs> OnChanged;
private readonly ConcurrentDictionary<int, Item> items = new ConcurrentDictionary<int, Item>();
public IItem GetOrCreateItemById(int id)
{
bool changed = false;
IItem result = items.GetOrAdd(int, CreateItem);
if (changed)
{
OnChanged?.Invoke(this, EventArgs.Empty);
}
return result;
IItem CreateItem(int key)
{
changed = true;
return new Item() { Id = key };
}
}
public bool TrySetItemMyProperty(int id, string newValue)
{
if (items.TryGet(id, out Item i))
{
if (i.TrySetMyProperty(newValue))
{
OnChanged?.Invoke(this, EventArgs.Empty);
return true;
}
}
return false;
}
}

Polymorphism without using the virtual keyword

Obviously using virtual and override is the normal situation, but does this telecoms'ish example count?
public class Pipe
{
// whole bunch of protected member variables such as bandwidth, latency, download limit
// etc,
public int GetCost()
{
// work out cost based on above
}
}
public class BigFatPipe : Pipe
{
public BigFatPipe()
{
// sets up the member variables one way
}
}
public class CheapestPossiblePipe: Pipe
{
public CheapestPossiblePipe()
{
// sets up the member variables another way
}
}
then you might call
PrintPrice(new BigFatPipe())
PrintPrice(new CheapestPossiblePipe())
public void PrintPrice(Pipe pipe)
{
int a = pipe.GetCost();
....
}
You'll get two different answers. This isn't the most useful example but does it count?
This post here has a useful discussion of what exactly polymorphism is.
I think most definitions do not explicitly state that an object must have virtual functions to be polymorphic - so yes, I think your example counts.
Constructor overloading is a recognized method to implement static polymorphism. While this isn't really constructor overloading, it's close. So yes, I'd call it polymorphism.
This pattern does work, but introducing a bunch of classes will confuse the user uselessly: they will wonder what the classes do differently.
A few factories methods will do the same job and will be easier to understand and maintain:
public class Pipe
{
// whole bunch of private member variables such as bandwidth, latency, download limit
// etc,
public int GetCost()
{
// work out cost based on above
}
public static Pipe MakeBigFatPipe()
{
var result = new Pipe();
// sets up the member variables one way
return result;
}
public static Pipe MakeCheapestPossiblePipe()
{
var result = new Pipe();
// sets up the member variables another way
return result;
}
}
If I were you I would use folowing approach:
public interface IGetCost
{
int GetCost();
}
public class Pipe : IGetCost
{
public int GetCost(){}
}
public class BigFatPipe : IGetCost
{
//aggregation
private readonly Pipe _pipe;
public BigFatPipe(Pipe pipe)
{
_pipe = pipe;
}
public int GetCost() { }
}
public class CheapestPossiblePipe : IGetCost
{
private readonly Pipe _pipe;
public CheapestPossiblePipe(Pipe pipe)
{
_pipe = pipe;
}
public int GetCost() { }
}
public static void PrintPrice(IGetCost obj)
{
int cost = obj.GetCost();
Console.WriteLine(cost);
}
static void Main(string[] args)
{
IGetCost p;
p = new Pipe();
PrintPrice(p);
p = new BigFatPipe();
PrintPrice(p);
p = new CheapestPossiblePipe();
PrintPrice(p);
}
I also need to say that there're two different things - polymorphism and overloading
polymorphism
public class foo
{
public virtual void foo1{/*....*/}
}
public class fooA : foo
{
public override void foo1{/*....*/}
}
public class fooB : foo
{
public new void foo1{/*....*/}
}
public class fooC : foo
{
//new is the default modifier
public void foo1{/*....*/}
}
overloading
public class foo{
public int foo1{/*....*/}
public int foo1(int a){/*....*/}
public int foo1(string a){/*....*/}
public int foo1(int a, string b){/*....*/}
}

Unit: Resolve generic service using object type at runtime

What i'm trying to accomplish is to have a single wcf service that has (for example) an Insert(ICommand command) method and can resolve a generic service that knows how to insert the underling object type.
Where's my (poor) attempt on a sandbox project.
Besides other flaws, this services allow to attempt to insert any ICommand.
I'm relative new Unit user and i was wondering if someone has a better way to accomplish this.
class Program
{
static void Main(string[] args)
{
var cmd = new SingleCommand();
var cmd2 = new DoubleCommand();
var s = new MyWcfService();
s.Insert(cmd);
s.Insert(cmd2);
Console.ReadKey();
}
}
public interface ICommand { }
public interface ICommandService
{
void Insert(ICommand command);
}
public interface ICommandService<in T> : ICommandService where T : ICommand
{
void Insert(T command);
}
public class SingleCommand : ICommand { }
public class DoubleCommand : ICommand { }
public class SingleCommandService : ICommandService<SingleCommand>
{
public void Insert(SingleCommand singleCommand)
{
Console.WriteLine("Inserted a SingleCommand");
}
void ICommandService.Insert(ICommand command)
{
Insert((SingleCommand)command);
}
}
public class DoubleCommandService : ICommandService<DoubleCommand>
{
public void Insert(DoubleCommand doubleCommand)
{
Console.WriteLine("Inserted a DoubleCommand");
}
void ICommandService.Insert(ICommand command)
{
Insert((DoubleCommand)command);
}
}
public static class Config
{
public static UnityContainer Container = new UnityContainer();
static Config()
{
Container.RegisterType<ICommandService, SingleCommandService>(typeof(SingleCommand).Name);
Container.RegisterType<ICommandService, DoubleCommandService>(typeof(DoubleCommand).Name);
}
}
public class MyWcfService
{
public void Insert(ICommand command)
{
var foo = Config.Container.Resolve<ICommandService>(command.GetType().Name);
foo.Insert(command);
}
}
If you really don't have a service that can be invoked for all ICommand, then you shouldn't offer that in its contract. An easy way around this is to extend the ICommand interface into something like IServiceCommand, and have those ICommand which are supported implement IServiceCommand instead, and tie your service contract instead to that interface. This allows your concrete classes to be used in any method which expects an ICommand, but your service still only service those ICommand which are also IServiceCommand.

Receiving dynamically changing classes

In my system I have 16 different classes alike used for statistics. They look like the following
public class myClass : myInheritage
{
private static myClass _instance;
public static myClass Instance
{
get { return _instance ?? (_instance = new myClass(); }
}
public static void Reset()
{
_instance = null;
}
}
They are all made into singletons
myInheritage looks like this:
public class myInheritage
{
int data = 0;
public myInheritage()
{
}
public int Data
{
get { return data; }
set { data+= value; }
}
}
The program is made, so the user chooses which class he wants to make statistics with.
Something like this is what I want
public void statistics(Object myObject, string name)
{
Object x = myObject;
x.Data = 10;
x.Data();
}
Called from another class
statistics(myClass.Instance, "myClass");
statistics(myClass2.Instance, "myClass2)";
So I want to dynamically change my instance in my statistics class.
Is that possible with .NET 2.0 ?
You could use reflection...
MethodInfo method = myObject.GetType().GetMethod("Reset");
if (method != null) method.Invoke(myObject, null);
If you can modify the classes themselves, a better approach might be to have each implement an interface (or base class) IResettable.
public interface IResettable
{
void Reset();
}
public class myClass : myInheritage, IResettable
{
public void Reset() { ... }
}
Then you could write the function against the interface:
public void statistics(IResettable myObject, string name)
{
myObject.Reset();
}
Yes. What you want here is a Strategy/Factory pattern. I name both as they could be used in conjunction for your case. There are great examples of these design patterns here and the following are detailed intros to the Strategy pattern and the Factory pattern. The former of the last two links also shows you how to combine the two to do exactly waht you require.
So in your case, you could set up the following interface
public interface IStatistics
{
// Some method used by all classes to impose statistics.
void ImposeStatistics();
}
Then in you singleton classes you could have
public class myClass : myInheritage, IStatistics
{
private static myClass _instance;
public static myClass Instance
{
get { return _instance ?? (_instance = new myClass()); }
}
public static void Reset()
{
_instance = null;
}
// You would also inherit from IStatistics in your other classes.
public void ImposeStatistics()
{
// Do stuff.
}
}
Then you would have a 'factory' class that imposes you stratgey at runtime.
public static class StatisticFactory
{
public static void ImposeStatistics(IStatistics statsType)
{
statsType.ImposeStatistics();
}
/// <summary>
/// Get the conversion type.
/// </summary>
/// <param name="col">The column to perform the conversion upon.</param>
public static IStatistics GetStatsType(string typeName)
{
switch (typeName)
{
case "BoseEinstein":
return new BoseEinsteinStats();
case "FermiDirac":
return new FermiDiracStats();
default:
return null;
}
}
}
You can then call this like
// Run stats.
IStatistics stats = StatisticFactory(GetStatsType("BoseEinstein"));
to get the statistics for the required class.
I hope this helps.

C# & Design Patterns - need an elegant solution for a common issue

I have 2 projects : The first project is a structure project which i read from an xml file.
This project is used in other solutions
The second project(1 of the other solutions) work on the structure project with foreach running on components list:
namespace FriendProject.Workers
{
public class Worker
{
static void Main(string[] args)
{
foreach (Component component in ComponentList)
{
DoWork(component);
}
}
}
}
Today the DoWork method does the following:
public void DoWork(Component component)
{
// Doing work on component properties
// Zip component files with open source Zipper
if (component is DBComponent)
{
// work on DBComponent properties
}
}
Now if you are familiar with design patterns then you can see that there is an injection point here and the following should be done :
public class Component
{
public virtual void DoWork()
{
// Do work
}
}
public class DBComponent : Component
{
public override void DoWork()
{
base.DoWork();
// injection point - work on DBComponent properties
}
}
public class Operator
{
static void Main(string[] args)
{
foreach (Component component in ComponentList)
{
component.DoWork();
}
}
}
The problem is that the project which holds the Component and DBComponent is a structure project which is used in other solutions and with other projects and I need to add the open source Zip dll to the project and it becomes more tightly coupled to the current project("FriendProject") and less usable. Not to talk about that the other projects will never use these methods(DoWork in Component and DBComponent)
Is there a better solution without changing much the design? Should I add an adpater?
If so please provide and example.
Thanks to all
Edit: Short Question
2 projects :
One is a manager project which acts on the second project.
Second is a structure project(read data from xml) which is reused with other projects.
I want to add methods and refernces(since of polymorphism) in the structure project(second project). However it feels wrong since the other projects that uses it will never use those methods and the added references.
Is there a better solution for how to do it?
Edit :
Removed the structure project code the shorten the question. this code was irrelavent since its classes(Component and DBComponent) appear next.
Easy (and with three different GOF design patterns).
Since we can't do anything with the components, we'll have to use the bridge pattern.
Let's define handlers:
public interface IHandlerOf<T> where T : Component
{
void DoWork(T component);
}
So now we can create a handler type for each component type that we want to handle. A DB component handler would look like this:
public class DbComponentHandler : IHandlerOf<DbComponent>
{
public void DoWork(DbComponent component)
{
// do db specific information here
}
}
But since we don't really want to keep track of all handlers we'll want to create a class that does it for us. We ultimately want to invoke the code just as in your example:
foreach (Component component in ComponentList)
{
handler.DoWork(component);
}
But let's make it a bit cooler:
//maps handlers to components
var service = new ComponentService();
// register all handlers in the current assembly
service.Register(Assembly.GetExecutingAssembly());
// fake a component
var dbComponent = new DbComponent();
// the cool part, the invoker doesn't have to know
// about the handlers = facade pattern
service.Invoke(dbComponent);
The service with makes it possible looks like this:
public class ComponentService
{
private readonly Dictionary<Type, IHandlerInvoker> _handlers = new Dictionary<Type, IHandlerInvoker>();
public void Register(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
if (type.IsInterface)
continue;
foreach (var interfaceType in type.GetInterfaces())
{
if (!interfaceType.IsGenericType || interfaceType.GetGenericTypeDefinition() != typeof(IHandlerOf<>))
continue;
var componentType = interfaceType.GetGenericArguments()[0];
var instance = Activator.CreateInstance(type);
var method = instance.GetType().GetMethod("DoWork", new[] { componentType });
_handlers[componentType] = new ReflectionInvoker(instance, method);
}
}
}
public void Register<T>(IHandlerOf<T> handler) where T : Component
{
_handlers[typeof (T)] = new DirectInvoker<T>(handler);
}
#region Nested type: DirectInvoker
private class DirectInvoker<T> : IHandlerInvoker where T : Component
{
private readonly IHandlerOf<T> _handler;
public DirectInvoker(IHandlerOf<T> handler)
{
_handler = handler;
}
#region IHandlerInvoker Members
public void Invoke(Component component)
{
_handler.DoWork((T) component);
}
#endregion
}
#endregion
#region Nested type: IHandlerInvoker
private interface IHandlerInvoker
{
void Invoke(Component component);
}
#endregion
#region Nested type: ReflectionInvoker
private class ReflectionInvoker : IHandlerInvoker
{
private readonly object _instance;
private readonly MethodInfo _method;
public ReflectionInvoker(object instance, MethodInfo method)
{
_instance = instance;
_method = method;
}
#region IHandlerInvoker Members
public void Invoke(Component component)
{
_method.Invoke(_instance, new object[] {component});
}
#endregion
}
#endregion
public void Invoke(Component component)
{
IHandlerInvoker invoker;
if (!_handlers.TryGetValue(component.GetType(), out invoker))
throw new NotSupportedException("Failed to find a handler for " + component.GetType());
invoker.Invoke(component);
}
}
Do note that the interface (IHandlerOf<T>) is generic which means that we can't store it directly in a Dictionary. Hence we use the Adapter pattern to store all handlers.
Full example:
public interface IHandlerOf<in T> where T : Component
{
void DoWork(T component);
}
public class ComponentService
{
private readonly Dictionary<Type, IHandlerInvoker> _handlers = new Dictionary<Type, IHandlerInvoker>();
public void Register(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
if (type.IsInterface)
continue;
foreach (var interfaceType in type.GetInterfaces())
{
if (!interfaceType.IsGenericType || interfaceType.GetGenericTypeDefinition() != typeof(IHandlerOf<>))
continue;
var componentType = interfaceType.GetGenericArguments()[0];
var instance = Activator.CreateInstance(type);
var method = instance.GetType().GetMethod("DoWork", new[] { componentType });
_handlers[componentType] = new ReflectionInvoker(instance, method);
}
}
}
public void Register<T>(IHandlerOf<T> handler) where T : Component
{
_handlers[typeof (T)] = new DirectInvoker<T>(handler);
}
#region Nested type: DirectInvoker
private class DirectInvoker<T> : IHandlerInvoker where T : Component
{
private readonly IHandlerOf<T> _handler;
public DirectInvoker(IHandlerOf<T> handler)
{
_handler = handler;
}
#region IHandlerInvoker Members
public void Invoke(Component component)
{
_handler.DoWork((T) component);
}
#endregion
}
#endregion
#region Nested type: IHandlerInvoker
private interface IHandlerInvoker
{
void Invoke(Component component);
}
#endregion
#region Nested type: ReflectionInvoker
private class ReflectionInvoker : IHandlerInvoker
{
private readonly object _instance;
private readonly MethodInfo _method;
public ReflectionInvoker(object instance, MethodInfo method)
{
_instance = instance;
_method = method;
}
#region IHandlerInvoker Members
public void Invoke(Component component)
{
_method.Invoke(_instance, new object[] {component});
}
#endregion
}
#endregion
public void Invoke(Component component)
{
IHandlerInvoker invoker;
if (!_handlers.TryGetValue(component.GetType(), out invoker))
throw new NotSupportedException("Failed to find a handler for " + component.GetType());
invoker.Invoke(component);
}
}
public class DbComponent : Component
{
}
public class DbComponentHandler : IHandlerOf<DbComponent>
{
public void DoWork(DbComponent component)
{
// do db specific information here
Console.WriteLine("some work done!");
}
}
internal class Program
{
private static void Main(string[] args)
{
var service = new ComponentService();
service.Register(Assembly.GetExecutingAssembly());
var dbComponent = new DbComponent();
service.Invoke(dbComponent);
}
}
If you're sure you want to split data structure and data operations, create separate worker class.
public interface IWorker
{
void DoWork();
}
public abstract Worker<T>: IWorker where T: Component
{
private T _component;
protected Worker(T component) {_component = component;}
public abstract void DoWork();
}
public class DbWorker: Worker<DbComponent>
{
public DbWorker(DbComponent component): base(component) {}
public override DoWork() {...}
}
and implement some factory to create specific workers from specific components.
Have you considered having Operator and Component packaged together, and DBComponent in a second project, as for the other projecs of the solution ? Then, you could use a light container such as Spring.net to configure your .exe and load the relevant assemblies.
It is the right thing to give your Component behaviours instead of having the worker class manipulating its properties.
If you don't want other project to see the doWork method, hide it behind an public interface and create an adapter from the public interface to your internal one.
public interface ComponentPublic {
void sharedMethod();
}
public class ComponentPublicAdapter implement ComponentPublic {
private Component component;
void sharedMethod() {
// Do something, may be call doWork()
}
}
Package the ComponentPublic interface in a different project/namespace, therefore other projects may interact with it without knowing the internal interface. Use a dependency injection framework or reflection to instantiate the adapter and Components.

Categories