Created
May 26, 2015 02:40
-
-
Save lukiffer/221f9424b22a9c5d085e to your computer and use it in GitHub Desktop.
Castle.Windsor Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel.Design.Serialization; | |
using Castle.MicroKernel.Registration; | |
using Castle.Windsor; | |
namespace CastleWindsorExample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var container = new WindsorContainer(); | |
container.Register( | |
Component.For<ExampleDependency>() | |
.LifestyleSingleton()); | |
container.Register( | |
Classes.FromThisAssembly() | |
.BasedOn<IExample>() | |
.WithServiceSelf() | |
.LifestyleTransient()); | |
container.Register( | |
Component.For<AnotherDependency>() | |
.LifestyleTransient()); | |
var example = container.Resolve<ExampleClass2>(); | |
example.DoStuff(); | |
example = container.Resolve<ExampleClass2>(); | |
example.DoStuff(); | |
example = container.Resolve<ExampleClass2>(); | |
example.DoStuff(); | |
example = container.Resolve<ExampleClass2>(); | |
example.DoStuff(); | |
example = container.Resolve<ExampleClass2>(); | |
example.DoStuff(); | |
example = container.Resolve<ExampleClass2>(); | |
example.DoStuff(); | |
Console.ReadKey(); | |
} | |
} | |
public interface IExample | |
{ | |
} | |
public class ExampleClass : IExample | |
{ | |
private readonly ExampleDependency _dependency; | |
public ExampleClass(ExampleDependency dependency) | |
{ | |
_dependency = dependency; | |
} | |
public void DoStuff() | |
{ | |
_dependency.SayHello(); | |
} | |
} | |
public class ExampleClass2 : IExample | |
{ | |
private readonly ExampleDependency _dependency; | |
private readonly AnotherDependency _another; | |
public ExampleClass2(ExampleDependency dependency, AnotherDependency another) | |
{ | |
_dependency = dependency; | |
_another = another; | |
} | |
public void DoStuff() | |
{ | |
_dependency.SayHello(); | |
_another.SaySomething(); | |
} | |
} | |
public class ExampleDependency | |
{ | |
private int counter = 0; | |
public void SayHello() | |
{ | |
Console.WriteLine("Hello from ExampleDependency: " + counter); | |
counter++; | |
} | |
} | |
public class AnotherDependency | |
{ | |
private int counter = 0; | |
public void SaySomething() | |
{ | |
Console.WriteLine("Hello from AnotherDependency: " + counter); | |
counter++; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment