Question

I want to add a logger to the Windows Form Application by using Castle IOC.

I registered the logger like below:

static class Program
{
    [STAThread]
    static void Main()
    {
        IWindsorContainer container = new WindsorContainer().Install(FromAssembly.This());

        container.Register(Component.For<ICommonLogger>().ImplementedBy(typeof(CommonLogger)).LifeStyle.Singleton);
        container.Kernel.Resolver.AddSubResolver(new EAE_Automation.COM.LoggerResolver(container.Kernel));

    } 
}  

Then another form of the application, I tried to use the logger as property but It comes null to the program.

namespace Test.KNXManagement
{
    public partial class Test: Form
    {
        public ICommonLogger Logger { get; set;} 

        public Tunneling()
        {
            Logger.Info("Testing.......................");

        }

    }
}

I think I am missing an important point here

Was it helpful?

Solution

I also register the Form class to resolve sub dependencies.

    container.Register(Classes.FromThisAssembly().BasedOn<Form>());

Then also run the application as below

    Application.Run(container.Resolve<Test>()); 

Thats solved my problem.

Thanks everyone.

OTHER TIPS

The following code, based on yours, works perfectly fine for me:

    private static IWindsorContainer _container;
    static Program()
    {
        Debug.Listeners.Add(new ConsoleTraceListener());

        _container = new WindsorContainer().Install(FromAssembly.This());

        _container.Register(Component.For<ICommonLogger>().ImplementedBy(typeof(CommonLogger)).LifeStyle.Singleton);
    }

    private static ICommonLogger Logger { get; set; }
    private static void Main(string[] args)
    {
        Logger = _container.Resolve<ICommonLogger>();

        Logger.Write("Text");

        Console.ReadLine();
    }

    public interface ICommonLogger
    {
        void Write(string str);
    }

    public class CommonLogger : ICommonLogger
    {
        public void Write(string str)
        {
            Console.WriteLine(str);
        }
    }

The output of the program in the console is Text.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top