我创建了一个MVC应用程序,它将调用WCF服务上的方法。我已将客户端应用程序配置为使用autofac,autofac.integration.mvc和autofac.integration.wcf。我使用以下autofac注册码:
var builder = new ContainerBuilder();
builder
.Register(c => new ChannelFactory<IUserService>())
.SingleInstance();
builder
.Register(c => new ChannelFactory<IUserService>(
new BasicHttpBinding(),
new EndpointAddress(@"http://localhost:36763/UserService.svc")))
.SingleInstance();
builder
.Register(c => c.Resolve<ChannelFactory<IUserService>>().CreateChannel())
.As<IUserService>()
.UseWcfSafeRelease();
但我希望能够避免对EndPoint地址进行硬编码。有没有办法在没有硬编码端点地址的情况下执行此操作?
更新。我尝试了下面列出的代码,无需硬编码端点地址。但它引入了对UserServiceClient的依赖。
var builder = new ContainerBuilder();
string endpointAddress;
using (var userServiceClientProxy = new UserServiceClient())
{
endpointAddress = userServiceClientProxy.Endpoint.Address.Uri.OriginalString;
}
builder
.Register(c => new ChannelFactory<IUserService>(
new BasicHttpBinding(),
new EndpointAddress(endpointAddress)))
.SingleInstance();
builder
.Register(c => c.Resolve<ChannelFactory<IUserService>>().CreateChannel())
.As<IUserService>()
.UseWcfSafeRelease();
builder.Register(l => LogManager.GetLogger(nameof(WcfClient2))).As<ILog>()
.SingleInstance();
builder.RegisterControllers(Assembly.GetAssembly(typeof(HomeController)));
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
答案 0 :(得分:0)
这是为配置文件(以及作为奖励,配置转换)制作的!大多数CI服务器和部署平台甚至都有重写配置值的机制,以保护您的开发环境免受生产。这只是一种很好的做法而且没有更好的方法,特别是考虑到除了你之外的人可能最终会在你正在建造的东西上工作,他们会希望看到熟悉的东西!