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();
}
}
通過以上最佳實踐,可以更好地管理依賴關系,提高代碼的可維護性和可測試性。