Hãy đầu tiên thừa nhận rằng bạn có một cái gì đó IProfileRepository như thế này:
public interface IProfileRepository
{
Profile GetProfile(string profileName);
}
cũng như hai triển khai: DatabaseProfileRepository
và XmlProfileRepository
. Vấn đề là bạn muốn chọn đúng giá trị dựa trên giá trị của profileType.
Bạn có thể làm điều này bằng cách giới thiệu này Abstract Factory:
public interface IProfileRepositoryFactory
{
IProfileRepository Create(string profileType);
}
Giả sử rằng các IProfileRepositoryFactory đã được tiêm vào việc thực hiện dịch vụ, bây giờ bạn có thể thực hiện phương pháp GetProfileInfo như thế này:
public Profile GetProfileInfo(string profileType, string profileName)
{
return this.factory.Create(profileType).GetProfile(profileName);
}
Triển khai cụ thể của IProfileRepositoryFactory có thể trông giống như sau:
public class ProfileRepositoryFactory : IProfileRepositoryFactory
{
private readonly IProfileRepository aRepository;
private readonly IProfileRepository bRepository;
public ProfileRepositoryFactory(IProfileRepository aRepository,
IProfileRepository bRepository)
{
if(aRepository == null)
{
throw new ArgumentNullException("aRepository");
}
if(bRepository == null)
{
throw new ArgumentNullException("bRepository");
}
this.aRepository = aRepository;
this.bRepository = bRepository;
}
public IProfileRepository Create(string profileType)
{
if(profileType == "A")
{
return this.aRepository;
}
if(profileType == "B")
{
return this.bRepository;
}
// and so on...
}
}
Bây giờ bạn chỉ cần lấy container DI của bạn lựa chọn để dây nó tất cả lên cho bạn ...
Nguồn
2010-01-30 18:18:36
Chuỗi tuần tự 'ifs' có thể được thay thế bằng' chuyển/trường hợp 'nhanh hơn/dễ đọc hơn. Và 'profileType' thực sự phải là một kiểu liệt kê, không phải là một chuỗi tùy ý. Khác hơn đó là một câu trả lời tuyệt vời. :) – Aaronaught
Có, không có bất đồng ở đó, nhưng tôi chỉ đi với API được đưa ra bởi OP :) –
Bằng cách nào nó có thể thay đổi nếu tôi không biết tại thời gian biên dịch số lượng kho? Và nếu wcf của tôi chỉ có phụ thuộc với thư viện đăng nhập và các kho lưu trữ này, thì lựa chọn DI Container tốt nhất ở đâu? là MEF là sự lựa chọn tốt trong trường hợp này? – tartafe