public interface IService
{
void DoSomething();
}
public class Service : IService
{
public void DoSomething()
{
// do something
}
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void UseService()
{
_service.DoSomething();
}
}
var builder = new ContainerBuilder();
builder.RegisterType<Service>().As<IService>();
var container = builder.Build();
var client = container.Resolve<Client>();
client.UseService();
builder.RegisterType<Service>().As<IService>().SingleInstance();
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void UseService()
{
_service.DoSomething();
}
}
public class Client
{
private readonly IService _service;
public Client(IService service)
{
_service = service;
}
public void UseService()
{
_service.DoSomething();
}
}
通过以上最佳实践,可以更好地管理依赖关系,提高代码的可维护性和可测试性。