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()
}
Related
I have the following setup:
public interface IRepository<T>
{
void Save(T entity);
}
public interface IEmailRepository : IRepository<Email> {} // completely empty!
public class MockRepository<T> : IRepository<T> {}
What I wish to do is the following:
void SomeBusinessMethod(IEmailRepository repo) { ... }
MockRepository<Email> mockRepository = CreateMockRepository<Email>();
IEmailRepository mockedEmailRepository = (IEmailRepository) mockRepository; // Invalid cast!
BusinessMethod(mockedEmailRepository);
I am aware that this isn't possible because MockRepository<T> does not inherit from IEmailRepository, even through the class and interface have the exact same signatures.
This is done in a production project and my goal is to inject a mock repository into business classes. I would prefer the possibility of using reflection to forcefully do this conversion anyways to not update the business logic code.
I found that you can use TypeBuilder and ModuleBuilder to create new types and methods with IL, but I just want to assign an interface to an instance that already sort of implements it. Is there a way to achieve this?
There are several other questions slightly related to this problem, but none have been answered with a solution that allows this setup.
In order to properly unit test some of my classes I need to mock the class objects being used by the main class being tested. This is a simple process if all the objects being used implements the interface and I only need to use the methods form that interface. However, and here is the problem:
Interfaces are a contract on what other developers should expect in that class. Therefore all interface methods, properties etc. are public. Any good code should also have good encapsulation. Therefore I don't want to make all methods in my class public and hence don't declare it in the interface. And as a result I can not mock and setup these internal method that is used in my main class.
Other options I looked into was using an abstract class that can have different access modifiers and I can have the correct methods in it be internal or private etc. But since I want the class being mocked to be available is a public property of interface type for other developers to use, I need it be an interface, but now its not compatible anymore since my main class cant call the internal method anymore as its defined as an interface. Catch 22. (In case you were wondering, using virtual for methods will have the same problem as using an abstract class).
I have searched for similar questions regarding C# mocking and did not find the same problem I have. And please don't be philosophical on "C# isn't good language for testing" or such stuff. That's not an answer.
Any ideas?
I added this code example to make it easier to see the problem described above.
[assembly: InternalsVisibleTo("MyService.Tests")]
public interface IMyService
{
MethodABC()
...
}
public class MyService : IMyService
{
public void MethodABC()
{
...
}
internal void Initialize()
{
...
}
...
}
public sealed partial class MyMain
{
public IMyService Service { get; private set; }
private MyService _service;
...
private void SomeMethod()
{
// This method is in interface and can be used outside the project when this assembly is referenced
_service.MethodABC()
...
// This method is and internal method inside the class not to be seen or used outside the project.
// 1) When running this method through unit test that mocked the IMyService will fail here since initialize don't exist which is correct.
// 2) Mocking the MyService will require "virtual" to be added to all methods used and don't provide a interface/template for a developers if
// they want to swap the service out.
// 3) Changing the interface to abstract class and mocking that allows for making this an internal method and also set it up in mock to do
// something for unit test and provides contract other developers can implement and pass in to use a different service, but requires
// "override" for all methods to be used from "outside" this assembly. This is best solution but require changes to code for sole purpose
// of testing which is an anti-pattern.
_service.Initialize()
...
}
}
// Unit test method in test project
[TestClass]
public class MyMainTests
{
private Mock<IMyService> _myServiceMock = new Mock<IMyService>();
[TestMethod]
public void MyMain_Test_SomeMethod()
{
...
SomeMethod()
...
}
}
Interface testing doesn't make sense. Interface doesn't say anything about "what it should do". When I need test something with interface, I make MockClass in my NUnit testing class. This class works only for few tests, and it is internal. If you have same namespaces for your tested class and your tests, there should be internal enough. So it is not public. But still you cannot test any private methods.
Sometimes it is annoying, but I cannot have nice code in my tests. But it is not strange.
I get the point of testing only public methods and properties but sometimes this limitation just makes no sense as well as using interfaces just to support unit tests.
My workaround is to inherit the class I am testing, add public access methods and then call protected base class members from it.
One option to consider is to specify the internal actions on an internal interface that you can then use to mock those actions. Given your example, you could add:
internal interface IInitialize
{
void Initialize();
}
And then implement this in your class alongside your public interface:
public class MyService : IMyService, IInitialize
And then your consuming class can use the interface as needed:
public sealed partial class MyMain
{
public MyMain(IMyService myService)
{
Service = myService;
}
public IMyService Service { get; }
public void SomeMethod()
{
(Service as IInitialize)?.Initialize();
Service.MethodABC();
}
}
Now in the unit test you can utilize the As<TInterface>() method in Moq to handle the multiple interfaces (read the docs):
[Fact]
public void Test1()
{
Mock<IMyService> myServiceMock = new Mock<IMyService>();
Mock<IInitialize> myServiceInitializeMock = myServiceMock.As<IInitialize>();
//myServiceMock.Setup(s => s.MethodABC()).Whatever
//myServiceInitializeMock.Setup(s => s.Initialize()).Whatever
MyMain myMain = new MyMain(myServiceMock.Object);
myMain.SomeMethod();
myServiceMock.Verify(s => s.MethodABC(), Times.Once);
myServiceInitializeMock.Verify(s => s.Initialize(), Times.Once);
}
Note the following remark on As<TInterface>():
This method can only be called before the first use of the mock
Moq.Mock`1.Object property, at which point the runtime type has
already been generated and no more interfaces can be added to it.
Also note that the use of As<TInterface>() also requires the following attribute to allow the mock proxy access to implement the internal interface:
[assembly:InternalsVisibleTo("DynamicProxyGenAssembly2")]
Unfortunately there don't seem to be a clean way of doing this. In order to create a mock using Moq, it needs to be either an interface, abstract class or virtual methods.
Interfaces cant have encapsulation lower than public. Using a internal interface will still force you to create "Public" methods.
Virtual methods allow access modifiers but do not provide an injectable object with a contract to be used by Moq other developers using the main class.
The ideal solution would not require code changes just for the purpose of making it unit testable. This unfortunately don't seem to be possible.
Which brings me to an abstract class that can provide a template (semi interface) that can be handled like an interface but will require "override" for all contract methods but at least will allow correct access modifiers for methods.
This still goes against clean code as I will need to add code to all my methods for the sole purpose of making it unit testable.
This is something Microsoft can look into for new .Net C# features. I will check if they have a feature request for this already.
Given:
public interface IFeedOperations : IOperationsWithPreInstalledData
{
...
}
public class FeedOperations : IFeedOperations
{
}
How do I use RegisterType for a class that implements IFeedOperations AND therefore the IOperationsWithPreInstalledData as well?
public class FeedsInstaller : IDependencyInstaller
{
public void Install(IDependencyContainer container)
{
container.RegisterType(typeof(IFeedOperations), typeof(FeedOperations));
container.RegisterType(typeof(IOperationsWithPreInstalledData), typeof(FeedOperations));
}
}
The current code yields the following error. And if I remove the second RegisterType then I get no results when I call container.ResolveAll<IOperationsWithPreInstalledData>().
Component ...Feeds.FeedOperations could not be
registered. There is already a component with that name. Did you want
to modify the existing component instead? If not, make sure you
specify a unique name.
And if I remove the second RegisterType then I get no results when I call container.ResolveAll<IOperationsWithPreInstalledData>(). Castle Windsor doesn't seem to see that a class implementing IFeedOperations also implements IOperationsWithPreInstalledData.
How can I register my implementing class with Castle Windsor so that it knows my class implements both interfaces -- or rather that either interface can be resolved by my class.
container.Register(Component.For<IFoo,IBar>().ImplementedBy<FooBar>());
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..
I am modifying some code that sits between two established layers, and am having trouble figuring out what the best design is.
Currently the code calls a file access library, and returns an object to the caller. I need to extend the returned object to add some custom dispose functionality. I don't have access to the definitions of the passed objects (some are filestreams, for example)
It would save me a lot of work if I could create a child instance that behaves like a base instance, and can be created from a base instance, but that has some hidden extra functionality. Can this be done without knowing the implementation details of the base class?
In code form that looks a lot like this:
private class FileObjectWithDispose : FileObject, IDisposable
{//voidaction is a delegate, this is .net 2.0
private VoidAction _disposeCallback;
public static FileObjectWithDispose wrapFile(FileObject unWrappedFile, VoidAction DisposeAction)
{//Implementation missing, this is the crux of what I don't know how to do
FileObjectWithDispose wrappedFile = new FileObjectWithDispose(unWrappedFile);
wrappedFile._disposeCallback = DisposeAction;
return wrappedFile;
}
private FileObjectWithDispose()
: base(null, null)//base class does not have a default constructor
{
throw new NotImplementedException("FileObjectWithDispose is a wrapper class which is intended only to be cast from a filestream.");
}
private void Dispose()
{
_disposeCallback();
base.Dispose();
}
}
a sample call would look like this:
Connect(file, username, password, domain);
return FileObjectWithDispose.wrapFile(OpenFile(path), () => { Disconnect(file, username); });
The key difficulty I'm having is, if it's possible, how do I take a base class instance and create a decorated instance if the base class does not implement an interface that allows itself to be decorated?
Any ideas how to accomplish this task?
Thanks!
The decorator pattern is the way to go.
Create an interface ICustomDisposeAction (an example name)
Implement this interface with all those possible classes which on you would want to perform DisposeAction on.
FileObjectWithDispose : FileObject, IDisposable, ICustomDisposeAction
Create another class Decorator which also implements ICustomDisposeAction. Pass the original base class through the constructor of the decorator and then call the decorator's DisposeAction on it.
public class Decorator : ICustomDisposeAction
{
public FileObject wrappedFile { get; set; }
public Decorator(FileObject unWrappedFile,...)
{
wrappedFile = unWrappedFile;
//Do your custom dispose here
}
}
In those situations which demands a custom way of disposing the object, create the decorator object and do the custom dispose!
Hope this helps.
Try use Decorator pattern. This link can help.