-
-
Notifications
You must be signed in to change notification settings - Fork 1
02. Basic usage
After installing Bindicate, you can start using it to automatically register your services.
Add the following line in your application's startup code to register all services decorated with Bindicate attributes:
builder.Services
.AddAutowiringForAssembly(Assembly.GetExecutingAssembly())
.Register();
Decorate your class with an attribute to register it with a specific lifetime.
[AddTransient]
public class SimpleTaskRunner
{
public void RunTask()
{
// Implementation
}
}
Decorate your class and specify the interface it implements
[AddScoped(typeof(IMyTaskRunner))]
public class TaskRunner : IMyTaskRunner
{
public void Run()
{
// Implementation
}
}
public interface IMyTaskRunner
{
void Run();
}
Keyed services enable resolving different implementations of the same interface based on a key.
Decorate your class with [AddKeyedScoped]
, [AddKeyedSingleton]
, or [AddKeyedTransient]
and provide the key.
[AddKeyedScoped("serviceA", typeof(IMyService))]
public class ServiceA : IMyService
{
// Implementation
}
[AddKeyedScoped("serviceB", typeof(IMyService))]
public class ServiceB : IMyService
{
// Implementation
}
Use the GetKeyedService
extension method.
var serviceA = serviceProvider.GetKeyedService<IMyService>("serviceA");
var serviceB = serviceProvider.GetKeyedService<IMyService>("serviceB");
Decorate your generic interface with [RegisterGenericInterface]
.
[RegisterGenericInterface]
public interface IRepository<T>
{
void Add(T entity);
}
Decorate your generic class and specify the open generic interface.
[AddTransient(typeof(IRepository<>))]
public class Repository<T> : IRepository<T>
{
public void Add(T entity)
{
// Implementation
}
}
Resolve the service for the specific type.
var customerRepository = serviceProvider.GetService<IRepository<Customer>>();
customerRepository.Add(new Customer());
Bindicate supports the TryAddEnumerable
method, allowing multiple implementations of an interface to be registered and resolved as IEnumerable<T>
.
Decorate each implementation with [TryAddEnumerable]
, specifying the lifetime and service type.
[TryAddEnumerable(Lifetime.TryAddEnumerableTransient, typeof(IMyService))]
public class MyServiceA : IMyService
{
// Implementation
}
[TryAddEnumerable(Lifetime.TryAddEnumerableTransient, typeof(IMyService))]
public class MyServiceB : IMyService
{
// Implementation
}
Inject IEnumberable<T>
into your consuming class.
public class MyController
{
private readonly IEnumerable<IMyService> _services;
public MyController(IEnumerable<IMyService> services)
{
_services = services;
}
public void ExecuteAll()
{
foreach (var service in _services)
{
service.Execute();
}
}
}