Access interface methods without referring the class - c#

Say I have an Interface like this in a project called "Interface":
public interface TestInterface
{
string Operation();
}
and class which implements it. This class is located in another project "Class":
public class TestClass : TestInterface
{
public TestClass() { }
public string Operation()
{
return "This is an Operation";
}
}
My client does something like this (which is again in a different project "Client"):
class Program
{
static void Main(string[] args)
{
TestInterface i = new TestClass();
i.Operation();
}
}
My question is related to this line:
TestInterface i = new TestClass();
By adding this line, I'm actually forced to add a references to both "Interface" as well as "Class" projects from my "Client" project. So why all this fuss? Can't I directly refer to the "Class" without keeping the "Interface" in between? Is there any way to access the methods via Interface only (without making a reference to the implementation Class)? Am I missing something here?

Is there any way to access the methods via Interface only
Yes, there is. You can dynamically load an assembly with TestClass without referencing it, create its instance via Activator.CreateInstance and cast it to interface type:
var assembly = Assembly.Load(...);
var typeFromAssembly = assembly.GetTypes()...;
var myInterfaceVar = (TestInterface)Activator.CreateInstance(typeFromAssembly);
...or... you may use one of existing DI-frameworks (e.g. MEF) and do the same thing more right way:
[Import]
private TestInterface myInterfaceField;
or:
var myInterfaceVar = compositionContainer.GetExportedValue<TestInterface>();
Depending of the way you prefer, you may ask more concrete question.

In that particular sample, there is no advantage.
But imagine a method:
public void Foo(ITestInterface handler)
{
handler.Operation();
}
Now, Foo operates only on the interface and it doesn't care what concrete class implements this interface. You could now call Foo with an instance of TestClass or with TestClass2, which could be defined in a different assembly.

you can achieve the behavior you have described via using IOC.
Unity is a dependency injection container which allows to create instances without manually creating instances.
For instance, if you were to register your class and interface to unity, you would directly use the interface;
TestInterface i = Container.Resolve<TestInterface>();

To make your code completely independent from implementation of TestInterface use Dependency Inversion. This could be achieved by some Dependency Injection framework.
E.g. with Unity you can configure implementation via xml
<register type="TestInterface"
mapTo="Foo.Bar.TestClass, Foo.Bar" />
And your code will depend only on Unity (no references to implementation):
TestInterface i = Container.Resolve<TestInterface>();

You have interface so that your app can have plug in's..
So basically you share your Interface dll to anyone who wants to make a plugin app for your app and then you can cast that new plugin class to the interface and invoke methods on it..
If you dont cast the class to the interface,how on earth are you going to make the plugin class work for your app..

Related

Implement interface to run a code at application Start

Sorry about the trouble guys, I have rephrased it as a new question here: MVC: Run a method on Application startup without calling it from Application_Start
This may be a very simple question but what's the best way to have an interface with a method OnStartup. When this interface is implemented, the OnStartup() code should run on application_start.
EDIT: I am actuall trying to create a HttpModule or something so that When I implement a particular class of this module, this class would have a method and by overriding this method, I will be able to run its code on application startup.
My only problem is that I don't want to call any code directly from application_start method.
P.S. If there is a nuget package available for this, please tell me the name.
Define your interface and class:
interface IOnStartup
{
void OnStartup();
}
class YourClass : IOnStartup
{
public void OnStartup()
{
}
}
Add in Global.asax
public void Application_OnStart()
{
var cls = new YourClass();
cls.OnStartup();
}
You cant run any code by implementing an interface you can just force your class to implement the code for OnStartup method
interface IOnStartup
{
void OnStartup();
}
class MyClass : IOnStartup
{
public void OnStartup()
{
// your code for OnStartUp method
// you are forced to implement the code for this method because your class implement IOnStartup
}
}
Or you can define an abstract class that implement this code and to inherit all classes that should have that method from this abstract class.
abstract class OnStartUpClass
{
public void OnStartup()
{
// the code for this method
}
}
class MyClass : OnStartUpClass
{
// implement code for this class
// you already have this method in your class
}
I think what you want to do is not achievable by implementing an interface. You should choose another way to do that.
If I understand you correctly, if there is a class that implements a given interface, you want that class to be instantiated and have it's OnStartup method called. If that is what you are trying to do then you have to rely on reflection.
In Application_Start call a method that will load all types present in your assembly and check if any of them implements that interface. If found you can instantiate an instance of it and call the method on that class.
If you want to add the class dynamically without recompiling your own application then it gets more complicated and involves creating AppDomains but it is also feasible.
EDIT
This question on stackoverflow tells you how to get all classes that implement an interface:
Getting all types that implement an interface
I would use an IOC container like Autofac, Ninject, Unity. Then you can register the interface with the framework and use the service locator to return all instances of classes that implement the interface.
//using Autofac
var builder = new ContainerBuilder();
containerBuilder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
var container = builder.Build();
var myItems = Container.Resolve<ISomeInterface>();
foreach(var item in myItems){
item.DoSomething()
}

Dynamic Namespace Switching

I'm attempting to put a web service wrapper around several third-party web services. For the sake of this question, we'll work with two of them:
OrderService
AddressService
Both of these services have the same object defined in different namespaces:
OrderService.AuthenticationParameters
AddressService.AuthenticationParameters
I was hoping to be able to create a single base class that would be able to detect/switch between namespaces. For example:
public abstract class BaseLogic
{
internal BaseLogic()
{
/* Initialize authParams */
//Switch out / detect namespace here
this.authParams = new OrderService.AuthenticationParameters();
this.authParams.accountName = "[MyAccountName]";
this.authParams.userName = "[MyUserName]";
this.authParams.password = "[MyPassword]";
}
}
I've seen several similar questions. Either they don't apply to my situation, or I'm incapable of understanding them.
Question: Is what I'm trying to achieve possible? If it's possible, am I over complicating things?
Additional Info: Eventally, there will be more than two services that share this common object. The vendor provides a separate service URL for each branch of functionality they provide.
There are quite a few solutions to this.
Have your service proxy classes implement your own interface to expose the methods, and then simply use reflection to build a type.
Wrap both services in another class that exposes the methods and has a reference to both services, then simply provide a switching argument to determine which to use.
Abstract the use of a service via your own interface and have classes coded against each service explicitly (see below).
Or if you want to play with dynamic and duck typing, this seemed to work:
namespace ConsoleApplication42
{
class Program
{
static void Main(string[] args)
{
Type t1 = Type.GetType("ProviderOne.AuthService");
dynamic service = Activator.CreateInstance(t1);
Console.WriteLine(service.GetUsername());
Type t2 = Type.GetType("ProviderTwo.AuthService");
service = Activator.CreateInstance(t2);
Console.WriteLine(service.GetUsername());
Console.Read();
}
}
}
namespace ProviderOne
{
public class AuthService
{
public string GetUsername()
{
return "Adam";
}
}
}
namespace ProviderTwo
{
public class AuthService
{
public string GetUsername()
{
return "Houldsworth";
}
}
}
Bear in mind they all hinge on both services having the same signature.
As for the other services in future, it really depends. I've never really encountered a need to dynamically switch from one service to another to get slightly different behaviour in achieving the same thing.
Perhaps this should be driven from your app's side? Instead of a service being chosen to suit, simply implement two versions of the class that has this changing behaviour - put a common interface on it, and decide which of your classes to use at runtime. The class itself will then be coded directly against one of the services.
interface IGetUsername
{
string GetUsername();
}
class UsernameViaProviderOne : IGetUsername
{
public string GetUsername()
{
return new ProviderOne.AuthService().GetUsername();
}
}
class UsernameViaProviderTwo : IGetUsername
{
public string GetUsername()
{
return new ProviderTwo.AuthService().GetUsername();
}
}
Then the decision is firmly in your client code and removes the need for reflection/dynamic typing:
IGetUsername usernameProvider = null;
if (UseProviderOne)
usernameProvider = new UsernameViaProviderOne();
...
To labour the point, you could always get very SOA and create yet another service that your app talks to that aggregates the other two services. Then at least your client code doesn't see the huge number of different services and talks to just one.
Hm, the only thing i can think of is to use reflection to create the object. The problem is that you have to use reflection again to set the properties, call methods etc., because i guess you don't have a shared interface. While its a lot of work and it might decrease the performance, it does the trick.
Have a look at the Activator with CreateInstance you can pass a full qualified class name and create your instance.
Then, using the Type of this new created object you can search for the properties you want to modify.
You may use #if.
#if true
using MyService.X;
using x=MyService.A;
#endif
#if false
using MyService2.X;
using x=MyService.B;
#endif
But you can not change in on run time as it works on compile time.
Note: Not a good programming practice. But this exists.

Looking for pattern to combine partial classes from different assembly's

I am having the following problem. I have a main project, and some extra projects that have similar functionality.
For example: I have an MVC website, then a class library project "A" with a "SettingsHelper". This just defines static wrappers for configuration settings so they can be used as propertys.
Then I have another class library project "B", which also contains a "SettingsHelper class".
How can I merge these SettingsHelpers in my main project, so I can use: SettingsHelper.Property from both modular extra projects.
I would like to be able to plug extra class libraries into one project.
Sounds pretty much like Dependency Injection. Normally you would expose SettingsHelper as an interface (your contract), and program against that. Then a DI container, such as Ninject, StructureMap, or Windsor would plug an implementation of that interface into the relevant parts of your code based on configuration.
This would allow you to code against a known contract and provide different libraries depending on the circumstances, the DI framework could then use that library to get the concrete implementation of the interface.
Would you need both instances at the same time?
Note that you cannot utilise the partial keyword across different assemblies, only within an assembly.
Update: based on your comment it sounds like you want to do something like Composition. Have a class that takes both classes from either library and combines them into one class that can be used by your application. Whether you then configure it to do something special or load the types when the libraries are present, it can all be encapsulated in this new class.
Update 2: alternatively, look into MEF:
http://msdn.microsoft.com/en-us/library/dd460648.aspx
That won't work. Partial classes cannot be divided over assemblies -- they don't exist in the CLR, only in the editor and the compiler. So they are compiled together into a single CLR class.
What you can do, is inherit one from the other. However, helpers tend to be static classes, so that won't work either.
The other alternative is not to write helper classes, but extension methods. You can extend classes in one assembly with methods defined in another assembly (or multiple other assemblies). See also http://msdn.microsoft.com/en-us/library/bb383977.aspx.
I would say that move both Helper classes in 3rd project and add reference of that project to both of your projects. So this new library will become shared datastructures and functionalities library.
Regards.
The specific pattern you are after is called a Facade Pattern. Unfortunately you are not going to get any help from the compiler getting this right. Essentially:
Create a new CombinedSettingsHelper class in your local assembly.
If the two SettingsHelper types are in the same namespace you will need to set up aliases for them (check the reference properties in the solution explorer, and MSDN documentation for this).
Implement the object so that it can access both SettingsHelper objects.
To clean up your facade you might try having a abstract method along the lines of abstract object GetSettingValue(string name);. Your facade could then inherit from the same base class and call these on its contained children. For example:
public abstract class SettingsHelperBase { public object GetSettingValue(string settingName); }
// Assembly1
public class SettingsHelper : SettingsHelperBase { }
// Assembly2
public class SettingsHelper : SettingsHelperBase { }
public class SettingsHelper : SettingsHelperBase
{
private List<SettingsHelperBase> _backends = new List<SettingsHelperBase>();
public readonly PropertiesImpl Properties;
public class PropertiesImpl
{
private SettingsHelper _settingsHelper;
public string Name
{
get
{
return (string)_settingsHelper.GetSettingValue("Name");
}
}
internal PropertiesImpl(SettingsHelper helper)
{
_settingsHelper = helper;
}
}
public SettingsHelper()
{
_backends.Add(asm1::MyNs.SettingsHelper);
_backends.Add(asm2::MyNs.SettingsHelper);
Properties = new PropertiesImpl(this);
}
protected override object GetSettingValue(string settingName)
{
foreach (var item in _backends)
{
var val = item.GetSettingValue(settingName);
if (val != null)
return val;
}
return null;
}
}
There is a way; Visual Studio allows the same code file to be included in more than one project.
When you do “Add”/”Existing Item” to can select a file that is in the different folder.
This is what some of the silver light support does so as to allow a “common class” that has some method that are only on the server and one methods that are only on the client.
(As to the question of “good design” you will have to decide that yourself, a lot of people don’t like having the same class compiled in different ways in different projects. Think if the mess you could get in with #if XXX, when XXX is only defined in one of the projects)

What's the best way to implement a dynamic proxy in C#?

I've got a need to create a dynamic proxy in C#. I want this class to wrap another class, and take on it's public interface, forwarding calls for those functions:
class MyRootClass
{
public virtual void Foo()
{
Console.Out.WriteLine("Foo!");
}
}
interface ISecondaryInterface
{
void Bar();
}
class Wrapper<T> : ISecondaryInterface where T: MyRootClass
{
public Wrapper(T otherObj)
{
}
public void Bar()
{
Console.Out.WriteLine("Bar!");
}
}
Here's how I want to use it:
Wrapper<MyRootClass> wrappedObj = new Wrapper<MyRootClass>(new MyRootClass());
wrappedObj.Bar();
wrappedObj.Foo();
to produce:
Bar!
Foo!
Any ideas?
What's the easiest way to do this?
What's the best way to do this?
Thanks so much.
UPDATE
I tried following Wernight's recommendation and implement this using C# 4.0 dynamic proxies. Unfortunately, I'm still stuck. The point of the proxy is to mimick the other interface which is (normally, usually) expected. Using DynamicObject requires me to change all the clients of this to use 'dynamic' instead of 'ISecondaryInterface'.
Is there a way to get a proxy object, such that when it wraps an A, it advertises (statically?) that it supports A's interface; and when it wraps a B, it advertises that is supports B's interface?
UPDATE 2
For example:
class MySecretProxy : DynamicObject, ISecondaryInterface
{
public override void TryInvokeMember(...) { .. }
// no declaration of Bar -- let it be handled by TryInvokeMember
}
.NET 4 DynamicObject can help you achieving that.
Earlier .NET framework can use:
Aspect#
Encase AOP
Spring.NET
Aspect.NET
AspectDNG
Dynamic Proxy
Compose*
Loom.NET
PostSharp
Each of these frameworks make use of a number
techniques to the injection of code
both before and after execution of a
method. These generally fall into 4
categories.
MSIL injection – Here we inject MSIL code into the body of the
method being executed. (Post sharp)
Runtime dynamic injection – Using techniques such as reflection we
invoke methods dynamically.
Type builder injection – Related to runtime injection, we create a type based on
the type we wish to proxy and then marshal requests through this type. (Dynamic Proxy)
Container injection – Requests pass through a container
which invokes code before and after our method being executed.
See the full article.
I know that Castle Project's Dynamic Proxy is often used (like in Moq just to name one large project).
REPLY TO UPDATED TOPIC
What you wrote will not compile. Dynamic proxies are runtime generated code, so you'll have to create a concrete instance of the class you're proxying some way or another. May be you're looking to do AOP (aspect-oriented programming).
class MySecretProxy<T> : DynamicObject, T where T : new()
{
private T _instance = new T();
public override void TryInvokeMember(...) { ... }
}
MySecretProxy<Bar> bar;
Have you looked at the Castle project's DynamicProxy? It may provide what you're ultimately trying to achieve. See http://www.castleproject.org/dynamicproxy/index.html
It's also open source so you could even fork it if required.
You can do this with RealProxy if the target Type is an interface or derives from MarshalByRefObject.
You may want to look at linfu which contains a dynamic proxy mechanism.
I know the proxies that used by nhibernate for lazy loading
Castle
Linfu
Spring ByteCode

How can I make a class global to the entire application?

I would like to access a class everywhere in my application, how can I do this?
To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.
Do you want to access the class or access an instance of the class from everywhere?
You can either make it a static class - public static class MyClass { } - or you can use the Singleton Pattern.
For the singleton pattern in its simplest form you can simply add a static property to the class (or some other class) that returns the same instance of the class like this:
public class MyClass
{
private static MyClass myClass;
public static MyClass MyClass
{
get { return myClass ?? (myClass = new MyClass()); }
}
private MyClass()
{
//private constructor makes it where this class can only be created by itself
}
}
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (Concrete instance or Static access to that class)
Or
You can have a Singleton class to use it everywhere but some people won't recommend you this way to proceed.
The other answers that you've been given about using a static class or a singleton pattern are correct.
Please consider, however, the fact that doing so does compromise your ability to test. In general, if you can, prefer dependency injection over globally accessed classes. I know this isn't always possible (or practical).
Just on that, you should also look up the abstract factory pattern. It allows you to have a well known factory class that produces the actual instance of a class that you're using. To have a globally accessed logging class, for example, don't directly create a logging class. Instead, use a logging factory to create it for you and return an interface to a logging class. That way it's easier to swap in and out different logging classes.
Since you do not want to create the object every time and it sounds like you are talking about some sort of utility methods...
I suggest you use static methods in an assembly which you can reference where needed

Categories

Resources