This is a complete dependency injection model with it's own container. .Net 5+ has it's own DI container and should be used instead of Specky. If you're using .NET 6 and up then preferably use Specky7, which is just a helper for the built in .NET IServiceCollection.
To start Specky up just call the boot strapper at the beginning of your application.
SpeckyAutoStrapper.Start();
If you want to Speck multiple assemblies you will need to reference those assemblies in this call.
SpeckyAutoStrapper.Start(new Assembly[]
{
typeof(Program).Assembly,
typeof(Global.Models.Dtos.PersonDto).Assembly
});
-
Add an interface.
public interface ILogger { void Log(string msg); }
-
Use interface.
public class Logger : ILogger { public void Log(string msg) { Console.WriteLine(msg); } }
-
Apply interface to any constructor.
public class Worker { ILogger Logger { get; } public Worker(ILogger logger) { Logger = logger; } }
-
Now simply add the [Speck] attribute to the class you want to inject and to the class that will recieve the injection.
[Speck] public class Logger : ILogger ... [Speck] public class Worker ...
Speck injection by configuration using Speck(configuration: "ConfigurationName").
Speck injection by name using SpeckName("NameofSpeck").
Speck injection using factories...
Make a SpeckyFactory by applying the [SpeckyFactory] attribute. In the example below Specky calls GetMapper to inject the IMapper dynamically and injects the appropriate speck for EntityConfigurer automatically when calling the method.
[SpeckyFactory]
public class EntityMapFactory
{
[Speck]
public IMapper GetMapper(EntityConfigurer entityConfigurer)
{
return new MapperConfiguration(entityConfigurer.ConfigureMappers).CreateMapper();
}
}
[Speck]
public class EntityConfigurer
{
public void ConfigureMappers(IMapperConfigurationExpression mapperConfigurationExpression)
{
CfgPersonDtoPerson(mapperConfigurationExpression);
}
private void CfgPersonDtoPerson(IMapperConfigurationExpression mapperConfigurationExpression)
{
mapperConfigurationExpression.CreateMap<PersonDto, Person>();
mapperConfigurationExpression.CreateMap<Person, PersonDto>();
}
}
Make a custom conditional [SpeckAttribute] that only injects specks that past a given test. (Note: By convention we add the keyword Speck before any custom attributes. This is not required but it will make your coworkers happy.)
-
Implement SpeckCondition into your own custom attribute.
public class SpeckX64Attribute : SpeckyConditionAttribute { public override bool TestCondition() { return Environment.Is64BitProcess; } } public class SpeckX32Attribute : SpeckyConditionAttribute { public override bool TestCondition() { return !Environment.Is64BitProcess; } }
-
Apply the attribute to any type that you want injected only if that condition is met.
[SpeckX64] public class LargeImageReader { ... } [SpeckX32] public class SmallImageReader { ... }