Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass dependency to object with Castle Windsor and MS Test?

I am trying to use Castle Windsor with MS Test. The test class only seems to use the default constructor. How do I configure Castle to resolve the service in the constructor?

Here is the Test Class' constructors:

private readonly IWebBrowser _browser;

        public DepressionSummaryTests()
        {

        }

        public DepressionSummaryTests(IWebBrowser browser)
        {
            _browser = browser;
        }

My component in the app config looks like so:

 <castle>
    <components>
      <component id="browser"
                 service="ConversationSummary.IWebBrowser, ConversationSummary"
                 type="ConversationSummary.Browser" />       

    </components>
  </castle>

Here is my application container:

public class ApplicationContainer : WindsorContainer
    {
        private static IWindsorContainer container;

        static ApplicationContainer()
        {
            container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
        }
        private static IWindsorContainer Container
        {
            get { return container; }
        }

        public static IWebBrowser Browser
        {
            get { return (IWebBrowser) Container.Resolve("browser"); }
        }
    }

MS test requires the default constructor. What am I missing?

Thanks!

like image 912
Nick Avatar asked Nov 30 '25 04:11

Nick


1 Answers

Since MSTest requires the default constructor it also means that it only uses this constructor. Thus, you can never get it to use the overloaded constructor. That's not an issue with Castle Windsor, but just the way MSTest works.

It's not that big of a deal though, because you shouldn't need to use a container for unit testing anyway.

When you use Windsor, you may want to consider using the Fluent Registration API instead of XML.

Another thing is that you shouldn't use a static Service Locator - it's an anti-pattern. This means that the ApplicationContainer class is redundant and should be deleted.

like image 106
Mark Seemann Avatar answered Dec 02 '25 17:12

Mark Seemann