I am using Teststack.White to launch and interact with a GUI.
The Model is hidden behind a facade, that allows a testing mock to be injected into the GUI. The GUI successfully loads the testing mock and Teststack.White can launch the application.
How can I access my singleton using the Teststack.White.Application or means of this sort.
/*Singleton in Mock.DLL that will allow test configurations*/
class Hook
{
public Hook SingleHook { get; private set; } = new Hook();
private Hook() { }
}
/*Loader in Nunit so far*/
private Application apploader()
{
ProcessStartInfo info = new ProcessStartInfo(#"C:\MyGUI\MYWPFGUI.exe");
info.WorkingDirectory = (#"C:\MyGUI\");
TestStack.White.Application app = Application.Launch(info);
return app;
}
I am currently investigating using AppDomains but since this Application is running in its won process i can not see how I would do that.
I need to get a hold of Singleton in order to setup and evaluate my tests.
I think the only way to do that is using some sort of inter process communication.
There are many example on google on here on SO here or here
You need to use reflection, first step is to Load the assembly that holds the Hook class by using Assembly.Load or Assembly.LoadFrom , then you use Assembly.CreateInstance or Activator.CreateInstance or AppDomain.CreateInstanceAndUnwrap methods and pass the Hook class type, now you cannot create the singleton from outside and then call CreateInstance to create it since it has private ctor, otherwise you need to use other means like GetMethod and Invoke from the Hook Singleton type to access its methods which is too much hassle.
However, i would suggest you create the class as normal class and hold a singleton instance in Test application, so make sure to mark your Hook class as public class with public constructor and in the Test project create a public static property/variable to hold the created class with reflection and then you can access the Singleton Hook class anywhere in the Test application by just calling the static property.
Related
Im beginning to learn about dependency injection and have decided to try to build my own (simple) logging facade as an introduction to it. So far I have the logging facade working with the basic functionality of NLog and log4net using Ninject.
(I know that Ninject has its own logging facade, but this is a learning exercise)
However I have run into a problem. What I want to do is to replicate what I log to file in a RichTextBox (Im using winforms). I am able to do this using NLog and log4net directly. The problem I have is that when Ninject wires up the interfaces it creates an implementation of a logger before the richtextbox on my winform has been created and consequently the logger does not find the richtextbox.
What I think I need to do is create the form then get Ninject to create the logger and inject it into the form, but I have no idea how to do this. Although I might be looking at this in completely the wrong way?
Please see below for the code im using to tie this together:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
IKernel kernel = new StandardKernel(new DI.NLog.Logger());
var form = kernel.Get<Form1>();
Application.Run(form);
}
}
and the constructor of my form is where the logger is injected.
public Form1(ILog log)
{
InitializeComponent();
_log = log;
}
Any help or advice would be appreciated.
Thank you
Here is one way to think about this:
First, make the form class implement ILog. What this means is that the form it self is a logging destination. When the logging methods are invoked on the form, write what you need to write to the RichTextBox control.
Now, the form itself is an ILog and it also depends on ILog. Also, I assume there is another ILog destination that you would like to log to, e.g., a Log4net adapter.
Here is how I imagine the object graph:
The arrow from X to Y means that X depends on Y, or that Y is injected into X.
The CompositeLog class is a composite ILog, it depends on multiple ILog objects, and when it is invoked to log something, it broadcasts such request to all the ILog dependencies.
As you see from the graph, we have a circular dependency. This can be solved by using Property Injection.
We can use Property Injection inside the CompositeLog class like this:
public class CompositeLog : ILog
{
private ILog[] logs;
public ILog[] Logs
{
set
{
if(logs != null)
throw new Exception("The logs dependencies has been set before");
logs = value;
}
}
public void LogInformation(string message)
{
foreach(var log in logs)
log.LogInformation(message);
}
//Other methods here
//...
}
Notice that this class does not take any dependencies on construction. We later can inject its dependencies via the Logs property.
If you are using Pure DI, your Composition Root would look like this:
var compositeLog = new CompositeLog();
Form1 form = new Form1(compositeLog);
compositeLog.Logs = new ILog[]{ form , new Log4NetAdapter()};
I don't know if this can be done with NInject easily. The bindings are probably going to be complex. In such cases where there are multiple implementations of a single interface, I think that DI containers fail. I suggest you use Pure DI.
Summary :
I have a DLL that hosts a class library. The library is used by an ASP.NET website. I need some code (initialization) to be run when the library is used. I have placed the code on the static constructor of one of the classes, which most likely will be used. It runs right now, but I was wondering
is there a better place to put this code? Some sort of DLL init
method?
are there any downfalls? If the class is never used, will the code
run anyways?
Details:
I have a DLL that hosts a class library that implements ECommerce to be used on ASP.NET websites. It contains controls and logic objects specific to my client. As part of it, it contains an HTTPhandler that handles AJAX calls to the library. The url that is associated with the Handler has to be registered. I have done this on the static constructor of one of the classes.
using System.Web.Routing;
class CMyClass {
static CMyClass() {
RouteTable.Routes.Insert(0, new Route("myapi/{*pathinfo}", new CMyHTTPHandlerRouter()));
}
}
This works right now. The site that uses the DLL does not have to register the route, which is very convenient. I was wondering, though:
is there a better place to register routes from a DLL? Or a better
way to associate a handler with a URL, directly from the DLL, so it
is always registered when the DLL is used.
are there any downfalls? If CMyClass is never used, will the code run anyways?
I can answer your second question: the static constructor will only run if you somehow interact with CMyClass. In other words, it's run on demand, not eagerly when you e.g. access the DLL.
Routes are to be construed as "application code". Meaning once it is "compiled" you cannot make changes to it. This is by design. Application_Start is the place where routes are normally registered.
I would normally abide by this convention. But my reusable logic (i.e. inside any publicly exposed method in the dll) should ensure that the routes are registered, else throw up an error. This is how the end developers know that they aren't using your component right. And if "it" knows the routes are registered it can safely go and execute the actual stuff.
I'd use a static boolean variable to accomplish that.
public class MyMvcSolution
{
public static bool Registered {get; set; }
static MyMvcSolution(){ Registered = false; }
public static void DoSomethingImportant()
{
if(Registered)
{
//do important stuff
}
else
throw new InvalidOperationException("Whoa, routes are not registered!");
}
//this should be called in the Application_Start
public static void Init()
{
RouteTable.Routes.Insert(0, new Route("myapi/{*pathinfo}", new CMyHTTPHandlerRouter()));
Registered = true;
}
}
I believe the above solution will kind of do.
There is an alternative strategy. We want to add routes "dynamically". This talks about forcing the BuildManager to register routes you mention is a .cs file. This file isn't "compiled" as part of the application; there will be a *.cs file in your application somewhere. You will make an assembly out of it on-the-fly, and from that force the buildmanager to register. There is also a mechanism to "edit" the routes once that file changes too. I'll leave it to you to explore this. Deep but interesting stuff.
I just started using the Unity Application Block to decouple my classes and make unit testing easier. However, I've run into a problem with circular dependencies.
I have a facade-type class which is a chat bot. It is a singleton class which handles all sort of secondary classes and provides a central place to launch and configure the bot. I also have a class called AccessManager which, well, manages access to bot commands and resources. Boiled down to the essence, I have the classes set up like so:
public class Bot
{
public string Owner { get; private set; }
public string WorkingDirectory { get; private set; }
private IAccessManager AccessManager;
private Bot()
{
// do some setup
// LoadConfig sets the Owner & WorkingDirectory variables
LoadConfig();
// init the access mmanager
AccessManager = new MyAccessManager(this);
}
public static Bot Instance()
{
// singleton code
}
...
}
And the AccessManager class:
public class MyAccessManager : IAccessManager
{
private Bot botReference;
public MyAccesManager(Bot botReference)
{
this.botReference = botReference;
SetOwnerAccess(botReference.Owner);
}
private void LoadConfig()
{
string configPath = Path.Combine(
botReference.WorkingDirectory,
"access.config");
// do stuff to read from config file
}
...
}
I would like to change this design to use the Unity Application Block. I'd like to use Unity to generate the Bot singleton and to load the AccessManager interface in some sort of bootstrapping method that runs before anything else does.
public static void BootStrapSystem()
{
IUnityContainer container = new UnityContainer();
// create new bot instance
Bot newBot = Bot.Instance();
// register bot instance
container.RegisterInstance<Bot>(newBot);
// register access manager
container.RegisterType<IAccessManager,MyAccessManager>(newBot);
}
And when I want to get a reference to the Access Manager inside the Bot constructor I can just do:
IAcessManager accessManager = container.Resolve<IAccessManager>();
And elsewhere in the system to get a reference to the Bot singleton:
// do this
Bot botInstance = container.Resolve<Bot>();
// instead of this
Bot botInstance = Bot.Instance();
The problem is the method BootStrapSystem() is going to blow up. When I create a bot instance it's going to try to resolve IAccessManager but won't be able to because I haven't registered the types yet (that's the next line). But I can't move the registration in front of the Bot creation because as part of the registration I need to pass the Bot as a parameter! Circular dependencies!! Gah!!!
This indicates to me I have a flaw in the way I have this structured. But how do I fix it? Help!!
You can make your life easier by changing the design in the following ways:
Don't implement the Singleton pattern yourself. The DI Container should manage the lifetime of all components, including the Bot class. If you only want a single instance in your application, configure Unity to always return the same instance.
Do everything in your power to remove circular dependencies. You can often do that by changing one of the communication directions to use events instead of direct calls. Another option is to introduce a Mediator.
Notice that none of these recommendations particularly involve Unity. Unity (or any other DI Container) is not a silver bullet that will magically make your code loosely coupled. You must first understand the principles behind DI, and then you can use any DI Container as a tool to help you wire up the dependency graph.
First of all you should let the container manage your singleton lifetime instead of writing the singleton code yourself. To remove your circular dependency, you can remove the Bot from the access manager constructor. Instead, you use an initialize method.
container.RegisterType<Bot>(new ContainerControlledLifecycleManager()); // from my memory...
container.RegisterType<IAccessManager,MyAccessManager>();
var bot = container.Resolve<Bot>();
// Bot.cs
public Bot(IAccessManager manager)
{
manager.InitializeFor(this);
}
For testability reasons you should never call your IOC container from a constructor.
I have a windows service that starts a thread in the OnStart method.
Basically I want to be able to stop the service if something goes really wrong (like an unhandled exception).
Currently I'm using ServiceBase.Stop() but that involves having a ServiceBase instance somewhere visible to the thread, which in turn involves having my instance be declared as public static in the main program.
Is there any "better way" to stop the service? If it isn't ... is it safe to do it that way?
The easiest and, in my opinion, cleanest way is to use a public static property of the service class. The only time this won't work is if you are using the same service class to run multiple services in the same process, something that is very rare.
private static MyService m_ServiceInstance;
public static MyService ServiceInstance
{
get { return m_ServiceInstance; }
}
public MyService()
{
InitializeComponents();
//Other initialization
m_ServiceInstance = this;
}
Injecting the service instance into every method that could possibly need it is an alternative but it can quickly get messy and it has no real advantages over just using a static property.
Check out the example here on how to use the ServiceController class to start and stop services.
Alternatively, you could pass your service instance to the thread when you create it (or set it as an instance variable in the thread class, etc.) without having to make your service class static.
A short example for completeness:
ServiceController sc = new ServiceController("MyService");
sc.Stop();
How to make it so if one copy of a program is running another won't be able to open?
Or better yet, how to make it so that if one copy is already running, then trying to run another copy will just act as if you maximized the original process?
Scott Hanselman wrote a post on doing this sort of thing
This article
True Single instance application - WinForms.NET
explains how to create a true single instance:
This article simply explains how you
can create a windows application with
control on the number of its instances
or run only single instance. This is
very typical need of a business
application. There are already lots of
other possible solutions to control
this.
e.g. Checking the process list with
the name of our application. But this
methods don't seems to be a good
approach to follow as everything is
decided just on the basis on the
application name which may or may not
be unique all across.
using System;
using Microsoft.VisualBasic.ApplicationServices;
namespace Owf
{
public class SingleInstanceController
: WindowsFormsApplicationBase
{
public SingleInstanceController()
{
// Set whether the application is single instance
this.IsSingleInstance = true;
this.StartupNextInstance += new
StartupNextInstanceEventHandler(this_StartupNextInstance);
}
void this_StartupNextInstance(object sender,
StartupNextInstanceEventArgs e)
{
// Here you get the control when any other instance is
// invoked apart from the first one.
// You have args here in e.CommandLine.
// You custom code which should be run on other instances
}
protected override void OnCreateMainForm()
{
// Instantiate your main application form
this.MainForm = new Form1();
}
}
}
Change you main function this way:
[STAThread]
static void Main()
{
string[] args = Environment.GetCommand
SingleInstanceController controller = new SingleInstanceController();
controller.Run(args);
}
Your best option is to use a named mutex. These articles explain the design pretty well and provide all the necessary code:
http://sanity-free.org/143/csharp_dotnet_single_instance_application.html
http://iridescence.no/post/CreatingaSingleInstanceApplicationinC.aspx
Extending this to maximise the main window of the running application should be a simple alteration to either of the examples provided.
You can use Mutex to make your app singleton. There are plenty of examples how to do it.
The Microsoft.VisualBasic.dll assembly contains a class 'WinformsFormsApplicationBase' which contains some functionality like the thing you want.
You can use this class in a C# application as well.
Just create a class which inherits from this class.
Set the SingleInstance property to true and override the necessary methods.
Offcourse, this means that you have a reference to the VisualBasic.dll assembly, which could be seen as a disadvantage, but, I think it is by far the most simple and easiest solution.
More info can be found here