以下是我正在处理的类和接口。
public interface IAccountService
{
//omitted for brevity...
}
public abstract class UserClientBase<T> : ClientBase<T> where T : class
{
protected UserClientBase(Binding binding, EndpointAddress remoteAddress, string userName, string password)
: base(binding, remoteAddress)
{
if (ClientCredentials == null) return;
ClientCredentials.UserName.UserName = userName;
ClientCredentials.UserName.Password = password;
}
}
public class AccountProxy : UserClientBase<IAccountService>, IAccountService
{
private static readonly WSHttpBinding Binding = WcfHelpers.ConfigureWsHttpBinding();
private static readonly EndpointAddress EndpointAddress =
new EndpointAddress(@"https://server.project.local/Project/Account/AccountService.svc");
public AccountProxy(string userName, string password)
: base(Binding, EndpointAddress, userName, password)
{
}
//omitted for brevity
}
public interface ISafeClient<out TService> : IDisposable where TService : class
{
//omitted for brevity...
}
public class SafeClient<TClient, TService> : ISafeClient<TService>
where TClient : UserClientBase<TService>, TService
where TService : class
{
//omitted for brevity...
}
public AccountController(ISafeClient<IAccountService> accountProxy)
{
_accountProxy = accountProxy;
}
我正在使用带有Autofac集成的Asp.net MVC 5,这里是我的Global.asax Application_Start方法中的注册。
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterType<AccountProxy>().As<IAccountService>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(SafeClient<,>)).As(typeof(ISafeClient<>)).InstancePerLifetimeScope();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
现在,当我尝试浏览AccountController处理的页面时,我在URL中收到以下异常。
没有找到的构造函数 类型上的'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' 'MyMvcApp.Controllers.AccountController'可以用。调用 可用的服务和参数:无法解析参数 “Project.Client.Proxies.ISafeClient`1 [Project.Client.Contracts.Service.IAccountService] accountProxy'的构造函数'Void
我不确定我在这里缺少什么。当我在运行时查看容器的ComponentRegistry时,我看到了Controllers和AccountProxy。提前谢谢。
更新 如果我这样注册它,我可以成功注入一个IAccountService:
builder.Register(a => new AccountProxy("userName", "password")).As<IAccountService>();
但是当我尝试注入ISafeClient时,我仍然会遇到异常。我想这里有一个更大的问题。本质上,我正在尝试包装ClientBase以包含安全处置和重试逻辑。它处理通信和消息异常,故障通道状态等。每次在SafeClient上执行方法时,ClientBase都会重新实例化,然后自动处理掉。如果是这种情况,我是否应该注射它?我很困惑。
更新2: 看起来我可以像这样注册。
builder.RegisterType<SafeClient<AccountProxy, IAccountService>>().As<ISafeClient<IAccountService>>().InstancePerLifetimeScope();
然后我的AccountController更改为:
private readonly ISafeClient<IAccountService> _accountProxy;
public AccountController(ISafeClient<IAccountService> accountProxy)
{
_accountProxy = accountProxy;
}
这样做是否有任何不利之处,除了明显需要单独注册安全客户端之外?