Hãy nói rằng tôi có một giao diện dịch vụ trông như thế này:Tại sao không phải suy luận kiểu làm việc trong mã này?
public interface IFooService
{
FooResponse Foo(FooRequest request);
}
Tôi muốn thực hiện một số lo ngại xuyên suốt khi gọi phương pháp trên các dịch vụ như thế này; ví dụ: tôi muốn ghi nhật ký yêu cầu hợp nhất, ghi nhật ký hiệu suất và xử lý lỗi. Biện pháp của tôi là phải có một cơ sở chung "Repository' lớp học với một phương pháp Invoke
rằng sẽ chăm sóc của cách gọi phương pháp này và làm những việc khác xung quanh nó lớp cơ sở của tôi trông giống như sau:..
public class RepositoryBase<TService>
{
private Func<TService> serviceFactory;
public RepositoryBase(Func<TService> serviceFactory)
{
this.serviceFactory = serviceFactory;
}
public TResponse Invoke<TRequest, TResponse>(
Func<TService, Func<TRequest, TResponse>> methodExpr,
TRequest request)
{
// Do cross-cutting code
var service = this.serviceFactory();
var method = methodExpr(service);
return method(request);
}
}
này hoạt động tốt Tuy nhiên , toàn bộ mục tiêu của tôi làm cho mã sạch bị cản trở bởi thực tế là suy luận kiểu không hoạt động như mong đợi Ví dụ, nếu tôi viết một phương pháp như thế này:.
public class FooRepository : BaseRepository<IFooService>
{
// ...
public BarResponse CallFoo(...)
{
FooRequest request = ...;
var response = this.Invoke(svc => svc.Foo, request);
return response;
}
}
tôi nhận được lỗi biên dịch này:
The type arguments for method ... cannot be inferred from the usage. Try specifying the type arguments explicitly.
Rõ ràng, tôi có thể sửa chữa nó bằng cách thay đổi cuộc gọi của tôi để:
var response = this.Invoke<FooRequest, FooResponse>(svc => svc.Foo, request);
Nhưng tôi muốn tránh điều này. Có cách nào để làm lại mã để tôi có thể tận dụng suy luận kiểu?
Edit:
Tôi cũng nên đề cập đến rằng một cách tiếp cận trước đó đã sử dụng một phương pháp khuyến nông; suy luận kiểu cho công việc này:
public static class ServiceExtensions
{
public static TResponse Invoke<TRequest, TResponse>(
this IService service,
Func<TRequest, TResponse> method,
TRequest request)
{
// Do other stuff
return method(request);
}
}
public class Foo
{
public void SomeMethod()
{
IService svc = ...;
FooRequest request = ...;
svc.Invoke(svc.Foo, request);
}
}
Tôi thấy; điều đó có ý nghĩa. – Jacob