I have a base class implementing an interface and further a specialized class inheriting the base class.
I have implemented interface's method in base class and marked it as virtual, also overridden the same method in specialized class.
Now i want to resolve the method GetData() on some basis that it either returns base class's method or child class's method.
So basically how can I call base class method using the specialized class's reference or interface's reference?
Edit 1
I have an existing data provider and I want to keep its functionality as it is and want to use some subclass or wrapper class where i can write a new implementation(another provider), mind that I want to keep running existing provider as it is for existing scenario and the new provider for other scenarios). what if i use decorator pattern to solve this? Any other pattern which can solve this ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
interface IDataProvider
{
void GetData();
}
abstract class StandardDataProvider : IDataProvider
{
public virtual void GetData()
{
Console.WriteLine("GetData_StandardDataProvider");
}
}
class ManagedDataProvider : StandardDataProvider
{
public override void GetData()
{
Console.WriteLine("GetData_ManagedDataProvider");
}
}
class Program
{
static void Main(string[] args)
{
IDataProvider dataprovider = new ManagedDataProvider();
dataprovider.GetData();
Console.ReadLine();
}
}
}
This is the only solution I could come up with for your problem:
interface IDataProvider
{
void GetData();
}
abstract class StandardDataProvider : IDataProvider
{
public virtual void GetData()
{
Console.WriteLine("GetData_StandardDataProvider");
}
}
class ManagedDataProvider : StandardDataProvider
{
public override void GetData()
{
Console.WriteLine("GetData_ManagedDataProvider");
}
public void GetBaseData()
{
base.GetData();
}
}
class Program
{
static void Main(string[] args)
{
IDataProvider dataprovider = new ManagedDataProvider();
dataprovider.GetData();
if (dataprovider is ManagedDataProvider)
{
(dataprovider as ManagedDataProvider).GetBaseData();
}
Console.ReadLine();
}
}
Another Way to attack it is adding GetBaseData to the Interface.
interface IDataProvider
{
void GetData();
void GetBaseData();
}
abstract class StandardDataProvider : IDataProvider
{
public virtual void GetData()
{
Console.WriteLine("GetData_StandardDataProvider");
}
public virtual void GetBaseData()
{
Console.WriteLine("GetData_StandardDataProvider");
}
}
class ManagedDataProvider : StandardDataProvider
{
public override void GetData()
{
Console.WriteLine("GetData_ManagedDataProvider");
}
public override void GetBaseData()
{
base.GetData();
}
}
class Program
{
static void Main(string[] args)
{
IDataProvider dataprovider = new ManagedDataProvider();
dataprovider.GetData();
dataprovider.GetBaseData();
Console.ReadLine();
}
}
C# Windows Form application.
I have an Hub and a class. Both should reference each other.
This is because:
from the hub I need to call the class' methods
from the class I need to retrieve my Hub
Right now I'm able to do the first point using Autofac:
using Autofac;
using Autofac.Integration.SignalR;
using Microsoft.AspNet.SignalR;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Hosting;
using Owin;
using MyProject.Classes;
using System;
using System.Reflection;
using System.Windows.Forms;
namespace MyProject
{
static class Program
{
static IDisposable webApp;
[STAThread]
static void Main()
{
string url = "http://localhost:8080";
webApp = WebApp.Start(url);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Engine());
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
var builder = new ContainerBuilder();
var config = new HubConfiguration();
builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired();
builder.RegisterType<Erp>().PropertiesAutowired().InstancePerLifetimeScope();
var container = builder.Build();
config.Resolver = new AutofacDependencyResolver(container);
app.UseAutofacMiddleware(container);
app.MapSignalR(config);
}
}
}
here the Hub:
using Microsoft.AspNet.SignalR;
using MyProject.Classes;
using System;
using System.Threading.Tasks;
namespace MyProject.Hubs
{
public class LiveHub : Hub
{
private readonly Erp _erp;
public LiveHub(Erp erp)
{
_erp = erp;
}
public override Task OnConnected()
{
_erp.someMethod();
return base.OnConnected();
}
}
}
and here Erp.cs:
public class Erp
{
public Erp()
{
}
public void SomeMethod()
{
// do something
}
public void SomeOtherMethod()
{
// usually I do:
var hub = GlobalHost.ConnectionManager.GetHubContext<LiveHub>();
hub.Clients.All.foo();
}
}
but here I read:
A common error in OWIN integration is use of the GlobalHost. In OWIN you create the configuration from scratch. You should not reference GlobalHost anywhere when using the OWIN integration. Microsoft has documentation about this and other IoC integration concerns here.
If I cannot use the "old" method, how should I retrieve my Hub?
I tried to add another DI in Erp for LiveHub but it doesn't work. In my form I create an instance of Erp:
public partial class Engine : Form
{
private Erp _erp = new Erp();
public Engine()
{
InitializeComponent();
}
}
if I add that DI the declaration will be impossible because I need to define the LiveHub in constructor, that requires itself the Erp parameter...
What am I not seeing?
You can decouple the Hub from the object (Erp in your case) by emitting events.
namespace MyProject.Hubs
{
public class LiveHub : Hub
{
public event Action SomethingHappened;
public override Task OnConnected()
{
SomethingHappened?.Invoke();
return base.OnConnected();
}
}
}
Now you can connect the Erp without the Hub having to know it. You will have to subscribe to the event somewhere else in your code. But the circular reference is broken.
To decouple Engine from Form you could do something like this:
public partial class EngineForm : Form
{
public EngineForm()
{
InitializeComponent();
}
}
public class Engine
{
public Engine(EngineForm form, Erp erp)
{
this.form = form;
this.erp = erp;
}
// Here is where you'll write some code to coordinate
// communication between the Erp and the EngineForm.
//
// The main advantage is that you can inject the Erp
// and have it preconfigured.
}
I'm building an API (for a game-engine) which exposes two interfaces called IWindow and IEngineWindow.
The IWindow interface is supposed to be implemented by an API-user and the IEngineWindow interface is used by the engine to interact with the window.
The window object should have a private member of the type List<IWindowControl>.
I could use an abstract class and get rid of the interfaces but then i would have implementation-details in my API which i don't want.
My theoretical solution to the problem is that the API-user implements IWindow in his own class and calls a method (something like GetEngineWindow(typeof(MyWindowClass))) which returns an object which is identical to an instance of MyWindowClass except that it also implements the IEngineWindow interface.
I was planning to use System.Reflection.Emit in the GetEngineWindow() method to dynamically combine MyWindowClass with an internal class which implements the IEngineWindow interface but i quickly realised that this would be a mayor project of it's own.
My question boils down to if there is a simpler solution to remove this kind of implementation-details from an API or if there exists a library (free for commercial use) to do this kind of class-fusing.
In case my question is too abstract, here is a code example of what i want to be able to do:
//API (dll-file)
interface IWindow
{
void BeforeClose();
}
interface IEngineWindow
{
void Show();
}
//Built into engine (written by me)
class Program
{
static void Main(string[] args)
{
object window = CombineClasses(typeof(Testwindow), typeof(EngineWindow));
((IWindow)window).BeforeClose(); //Outputs: Closing...
((IEngineWindow)window).Show(); //Outputs: Showing window...
}
}
class EngineWindow : IEngineWindow
{
public void Show()
{
Console.WriteLine("Showing window...");
}
}
//External assembly (dll-file)
class Testwindow : IWindow
{
public void BeforeClose()
{
Console.WriteLine("Closing...");
}
}
This sounds like you need a wrapper.
Let your internal class take an IWindow instance in its constructor
store it in a private field
implement both interfaces
and forward all IWindow members to the internal instance
Update: if you consider CastleWindsor a simpler approach, here it is (using xUnit for tests):
namespace Mixins
{
using System;
using Castle.DynamicProxy;
using Xunit;
public interface IA
{
void Do();
}
public interface IB
{
void Something();
}
public class A : IA
{
public void Do()
{
throw new NotImplementedException("A");
}
}
public class B : IB
{
public void Something()
{
throw new NotImplementedException("B");
}
}
public class Blender
{
[Fact]
public void Mix()
{
var options = new ProxyGenerationOptions();
// the instances for A and B would be the user provided and yours
options.AddMixinInstance(new A());
options.AddMixinInstance(new B());
var proxy = new ProxyGenerator().CreateClassProxy<object>(options);
Assert.IsAssignableFrom<IA>(proxy);
Assert.IsAssignableFrom<IB>(proxy);
try
{
((IA)proxy).Do();
}
catch (NotImplementedException ex)
{
if (ex.Message != "A")
{
throw;
}
}
try
{
((IB)proxy).Something();
}
catch (NotImplementedException ex)
{
if (ex.Message != "B")
{
throw;
}
}
}
}
}
I am the author of NCop - A composite-aspect framework that can help you achieve your goal.
NCop wiki
You basically need to create a new composite type interface that will implement both of your window interfaces and mark it as a composite using the TransientComposite attribute.
[TransientComposite]
public interface ICompositeWindow : IWindow, IEngineWindow
{
}
Order NCop to match between interfaces and implementations using Mixins attribute.
[TransientComposite]
[Mixins(typeof(EngineWindow), typeof(Testwindow))]
public interface ICompositeWindow : IWindow, IEngineWindow
{
}
create a CompositeContainer that will emit the new type.
class Program
{
static void Main(string[] args) {
ICompositeWindow window = null;
var container = new CompositeContainer();
container.Configure();
window = container.Resolve<ICompositeWindow>();
window.Show();
window.BeforeClose();
}
}
your final code should be:
using System;
using NCop.Composite.Framework;
using NCop.Mixins.Framework;
using NCop.Composite.Runtime;
namespace NCop.Samples
{
[TransientComposite]
[Mixins(typeof(EngineWindow), typeof(Testwindow))]
public interface ICompositeWindow : IWindow, IEngineWindow
{
}
public interface IWindow
{
void BeforeClose();
}
public interface IEngineWindow
{
void Show();
}
public class EngineWindow : IEngineWindow
{
public void Show() {
Console.WriteLine("Showing window...");
}
}
public class Testwindow : IWindow
{
public void BeforeClose() {
Console.WriteLine("Closing...");
}
}
class Program
{
static void Main(string[] args) {
ICompositeWindow window = null;
var container = new CompositeContainer();
container.Configure();
window = container.Resolve<ICompositeWindow>();
window.Show();
window.BeforeClose();
}
}
}
I've implemented a very small plugin system based on C# with MEF. The problem is, none of my plugins are instanced. In the Aggregate-Catalog I can see my plugin listed. But, after I'll compose these parts, there isn't my plugin in the plugin list, what I'm doing wrong?
Here's a snippet of my code:
Plugin-Loader:
[ImportMany(typeof(IFetchService))]
private IFetchService[] _pluginList;
private AggregateCatalog _pluginCatalog;
private const string pluginPathKey = "PluginPath";
...
public PluginManager(ApplicationContext context)
{
var dirCatalog = new DirectoryCatalog(ConfigurationManager.AppSettings[pluginPathKey]);
//Here's my plugin listed...
_pluginCatalog = new AggregateCatalog(dirCatalog);
var compositionContainer = new CompositionContainer(_pluginCatalog);
compositionContainer.ComposeParts(this);
}
...
And here, the plugin itself:
[Export(typeof(IFetchService))]
public class MySamplePlugin : IFetchService
{
public MySamplePlugin()
{
Console.WriteLine("Plugin entered");
}
...
}
Tested working sample.
Compile class library with code inside PluginNameSpace namespace and place it to the 'Test' folder which will be inside console app exe folder.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using ConsoleApplication;
namespace ConsoleApplication
{
public interface IFetchService
{
void Write();
}
class PluginManager
{
[ImportMany(typeof(IFetchService))]
public IFetchService[] PluginList;
public PluginManager()
{
var dirCatalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Test");
var pluginCatalog = new AggregateCatalog(dirCatalog);
var compositionContainer = new CompositionContainer(pluginCatalog);
compositionContainer.ComposeParts(this);
}
}
class Program
{
static void Main(string[] args)
{
var pluginManager = new PluginManager();
foreach (var fetchService in pluginManager.PluginList)
{
fetchService.Write();
}
Console.ReadKey();
}
}
}
// Separate class library
namespace PluginNameSpace
{
[Export(typeof(IFetchService))]
public class MySamplePlugin : IFetchService
{
public void Write()
{
Console.WriteLine("Plugin entered");
}
}
}
I know I can put my enum at the Namespace area of a class so everyone can access it being in the same namespace.
// defined in class2
public enum Mode { Selected, New, }
What I want is to access this enum from
public class1
{
var class2 = new class2();
// Set the Mode
class2.Mode = Model.Selected
}
Is this somehow possible without using namespace area?
You can declare an enum outside of a class:
namespace MyNamespace
{
public enum MyEnum
{
Entry1,
Entry2,
}
}
And then you can add using MyNamespace; where it needs to be used.
Aaron's answer is very nice but I believe there is a much better way to do this:
public static class class1
{
public void Run()
{
class2.Mode mode = class2.Mode.Selected;
if (mode == class2.Mode.Selected)
{
// Do something crazy here...
}
}
}
public static class class2
{
public enum Mode
{
Selected,
New
}
}
No point over complicating this. It is a simple task.
All the Best
Chris.
If you are trying to do what is described below it will not work...
public class MyClass1
{
private enum Mode { New, Selected };
public Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will not work due to protection level
myClass1.ModeProperty = MyClass1.Mode.
}
}
What you could do however is below, which will work...
public interface IEnums
{
public enum Mode { New, Selected };
}
public class MyClass1
{
public IEnums.Mode ModeProperty { get; set; }
}
public class MyClass2
{
public MyClass2()
{
var myClass1 = new MyClass1();
//this will work
myClass1.ModeProperty = IEnums.Mode.New;
}
}
Yes:
class2.Mode = class2.Mode.Selected
But note that you can't have a nested type defined that has the same name as one of the outer class' members, so this code will not compile. Either the enum or the property will need to be named something else. Your class name and variable name conflict too, making this a bit more complex.
To make this a more generic answer, if you have this:
public class Foo
{
public SomeEnum SomeProperty { get; set; }
public enum SomeEnum {
Hello, World
}
}
Then this code will assign an enum value to the property:
Foo foo = new Foo();
foo.SomeProperty = Foo.SomeEnum.Hello;
I ended up solving my issue by changing it to a namespace accessor, found by utilizing Intellisense. I thought the enum was in the class, not just the namespace. If it was in the class, I would recommend moving it out of the class.
namespace ABC.XYZ.Contracts
{
public class ChangeOrder : BaseEntity, IAuditable
{
...
}
public enum ContractorSignatureType
{
A,
B,
V
}
}
ContractorSignatureType = Contracts.ContractorSignatureType.B,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine((int)temp.names.nikk);
Console.ReadKey();
}
}
}
//by using this you can access the value of enum.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace #enum
{
class temp
{
public enum names
{
mohitt,
keval,
Harshal,
nikk
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(temp.names.nikk);
Console.ReadKey();
}
}
}