This is a very lightweight IOC implementation.
The configuration can be read as json file:
"DIConfiguration": {
"Register":
[{
"Contract":"Contracts.ITest",
"Implementation": "Concretes.Implementation"
},{
"Contract":"Contracts.IExample2",
"Implementation": "Concretes.Example"
}]
}
This configuration can be bind to the configuration class LightweightIOC.Configuration.DIConfiguration:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var config = builder.Build();
var appConfig = new DIConfiguration();
config.GetSection("DIConfiguration").Bind(appConfig);
LightweightIOC.DIContainer container = new SimpleIOC.DIContainer();
container.ReadConfiguration(appConfig);
The core domain builder is implemented in the class LightweightIOC.DIContainer.
- Registration with type objects
LightweightIOC.DIContainer container = new LightweightIOC.DIContainer();
container.Register(typeof(Contracts.ITest), typeof(Concretes.Implementation));
- Registration with generic functions
LightweightIOC.DIContainer container = new LightweightIOC.DIContainer();
container.Register<Contracts.ITest, Concretes.Implementation>();
The registered interfaces can be resolved via calling the resolve method:
object implementation = container.Resolve(typeof(Contracts.ITest));
If casting to the needed interface is necessary, a generic resolving method is available:
Contracts.ITest implementation = container.Resolve<Contract.ITest>();
To verify to ensure all registered types can be resolved, call the method Verify()
:
var appConfig = new DIConfiguration();
appConfig.Verify();
The method will throw an exception in case of an not found type.
Call method "IsRegistered":
var appConfig = new DIConfiguration();
appConfig.IsRegistered(typeof(IMyLocalInterface));
During creation of an implementation, all known interfaces will be filled with concrete implementations.
interface ITest { }
interface IExample { }
class Test : ITest { }
class Example : IExample
{
public Example(ITest test) { }
}
On resolving IExample the constructor of its implementation (Example) will be supplied with the implementation (Test) of the interface ITest.