public
Last active

Configuration by Convention using Ninject.Extensions.Conventions

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
void Main()
{
// 4 from your Compositon Root ...
using(var kernel = InitializeKernel())
{
// 4.1 resolve delivery services by names
var upsWorldShip = kernel.Get<IShippingCompanyService>("ShippingUpsWorldShip");
var fedExDesktopApps = kernel.Get<IShippingCompanyService>("ShippingFedExDesktopApps");
// 4.2 delivery processing
upsWorldShip.Delivery();
fedExDesktopApps.Delivery();
// 5 PROFIT!
}
}
 
// 1 define "delivery" interface
interface IShippingCompanyService
{
void Delivery();
}
 
// 2.1 — first assembly "Ups.Services.dll"
public class ShippingUpsWorldShip : IShippingCompanyService
{
public void Delivery()
{
"Ship with UPS WorldShip".Dump();
}
}
 
// 2.1 — first assembly "Ups.Services.dll"
public class ShippingFedExDesktopApps : IShippingCompanyService
{
public void Delivery()
{
"Ship with FedEX Desktop Apps".Dump();
}
}
 
// 3 kernel configuration
public static IKernel InitializeKernel()
{
var kernel = new StandardKernel();
 
kernel.Bind(x => x
// 3.1 search in current assembly
.FromThisAssembly()
.SelectAllClasses() // 3.2 select all classes implement "special" interface
.InheritedFrom<IShippingCompanyService>()
// 3.3 search all assemblies by wildcards
.Join.FromAssembliesMatching("./*Services.dll")
.SelectAllClasses() // 3.2 select all classes implement "special" interface
.InheritedFrom<IShippingCompanyService>()
// 3.4 bind to "special" interface
.BindAllInterfaces()
// 3.5 configure lifetime management and dependency name
.Configure((b, c) =>
b.InTransientScope().Named(c.Name)));
 
return kernel;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.