Skip to content

Instantly share code, notes, and snippets.

@manadart
Created March 25, 2011 08:22
Show Gist options
  • Save manadart/886534 to your computer and use it in GitHub Desktop.
Save manadart/886534 to your computer and use it in GitHub Desktop.
Example usage of TinyIoC - the first with constructor injection, the second with property injection.
namespace TinyIoCDemo
{
// This is the interface for my aspect - the dependency for my classes.
public interface IAspectDependency
{
string GetGreeting();
}
// And here is an implementation.
public class GreetingAspect : IAspectDependency
{
#region IAspectDependency Members
public string GetGreeting()
{
return "Hello World!";
}
#endregion
}
}
namespace TinyIoCDemo
{
// My greeting class that gets its greeting aspect via the constructor.
public class GreetingWithDependencyCi
{
private readonly IAspectDependency _greeting;
public GreetingWithDependencyCi(IAspectDependency greeting)
{
_greeting = greeting;
}
public string GetGreeting()
{
return _greeting.GetGreeting();
}
}
}
using TinyIoC;
namespace TinyIoCDemo
{
public static class Bootstrap
{
public static void Register()
{
// This is a single instance registration.
// When I ask the container for an IAspectDependency, is will always provide the same GreetingAspect.
TinyIoCContainer.Current.Register<IAspectDependency>(new GreetingAspect());
// This is a concrete type registration.
// When I ask the container for one of these, it will build me one each time.
TinyIoCContainer.Current.Register<GreetingWithDependencyCi>();
}
}
public static class Program
{
public static void RunProgram()
{
Bootstrap.Register(); // Register all my types in the container.
var greeting = TinyIoCContainer.Current.Resolve<GreetingWithDependencyCi>(); // Ask the container for the type;
System.Console.WriteLine(greeting.GetGreeting()); // Dependencies have been injected and everything works.
}
}
}
namespace TinyIoCDemo
{
// My greeting class that gets its greeting aspect via the constructor.
// Functionality is exactly the same as GreetingWithDependencyCi.
public class GreetingWithDependencySi
{
public IAspectDependency Greeting { get; set; }
public GreetingWithDependencySi()
{
// Maybe some construction work here.
}
public string GetGreeting()
{
return Greeting.GetGreeting();
}
}
}
using TinyIoC;
namespace TinyIoCDemo
{
public static class Program2
{
public static void RunProgram()
{
Bootstrap.Register(); // Register all my types in the container. Same bootstrap as in CiResolution.
var greeting = new GreetingWithDependencySi(); // Pretend we acquired this instance externally.
TinyIoCContainer.Current.BuildUp(greeting); // Ask the IoC container to "fill it in".
System.Console.WriteLine(greeting.GetGreeting()); // Dependencies have been injected and everything works.
}
}
}
@frantel90
Copy link

Usefull samples.

@kkostenkov
Copy link

Thank you for those.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment