我不确定这是否可能,我可能需要为每个实现编写扩展方法。下面是一些示例代码:扩展方法返回接口的正确实现吗?
public interface IBaseService<T>
{
IUnitOfwork UnitOfWork {get;}
}
public interface IService<T>: IBaseService<T>
{
IEnumerable<T> GetAll();
T GetById(Guid id);
}
public interface IUserService: IService<User>
{
User FindByUsernameAndPassword(string username, string password)
}
public class BaseService<T>: IService<T>
{
public BaseService(IRepository<T> repository)
{
_repository = repository
}
public virtual IEnumerable<T> GetAll(){....};
public virtual T GetById(Guid id){....};
IUnitOfWork UnitOfWork {get {return _repository.UnitOfWork;}}
}
public class UserService: BaseService<User>, IUserService
{
...
}
public static class ServiceExtensions
{
public static IBaseService<T> EnableLazyLoading<T>(this IBaseService<T> service, bool lazyLoad = True)
{
service.UnitOfWork.EnableLazyLoad(lazyLoad);
return service;
}
}
因此,假设我正在使用UserService。当我打电话的扩展方法上UserService,是有可能有它返回IBaseService的正确执行或做我需要为每个执行?:
实例创建和扩展方法:
userService.EnableLazyLoading(false).FindByUsernameAndPassword("ddivita","123456")
所以,澄清,你是说你想要它创建一个新的版本,无论它被称为? –
我只想编写一个扩展方法供IBaseServcie的所有实现使用,以便返回正确的实现。在我的例子中,我想找出一种方法来在我调用EnableLazyLoading扩展时返回IUserService。 –
DDiVita
哦!我明白了,所以你希望它返回被调用的特定类型,而不是创建它的新实例。 –