Last active
March 31, 2020 23:08
-
-
Save thiagosgarcia/7cffe5a09d1d1a8c6574243d5940e038 to your computer and use it in GitHub Desktop.
HttpBinding WCF injection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class HttpBindingExtensions | |
{ | |
public static BasicHttpBinding Https => new BasicHttpBinding | |
{ | |
MaxReceivedMessageSize = int.MaxValue, | |
MaxBufferSize = int.MaxValue, | |
Security = new BasicHttpSecurity() | |
{ | |
Mode = BasicHttpSecurityMode.Transport | |
} | |
}; | |
public static BasicHttpBinding Http => new BasicHttpBinding | |
{ | |
MaxReceivedMessageSize = int.MaxValue, | |
MaxBufferSize = int.MaxValue | |
}; | |
public static IServiceCollection AddWcfClient<I, T>(this IServiceCollection services, string key) | |
where I : class | |
where T : class, I | |
=> services.AddScoped<I>(x => GetWcfInstance<I, T>(key, x)); | |
private static T GetWcfInstance<I, T>(string key, IServiceProvider x) where I : class where T : class, I | |
{ | |
var type = typeof(T); | |
var ctorInfo = type.GetConstructor(new[] { typeof(BasicHttpBinding), typeof(EndpointAddress) }); | |
var config = (IConfiguration)x.GetService(typeof(IConfiguration)); | |
var instance = (T)ctorInfo?.Invoke(new object[] { config.GetHttpBinding(key), config.GetEndpointAddress(key) }); | |
return instance; | |
} | |
public static EndpointAddress GetEndpointAddress(this IConfiguration config, string key) | |
{ | |
return new EndpointAddress(config[key]); | |
} | |
public static BasicHttpBinding GetHttpBinding(this IConfiguration config, string key) | |
{ | |
return GetHttpBinding(config[key]); | |
} | |
public static BasicHttpBinding GetHttpBinding(string uri) | |
{ | |
return uri.StartsWithIgnoreCase("https") ? Https : Http; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment