HttpClient wrapper with Autofac for Web API - c#-4.0

I have inherited a stub project which is a HttpClient wrapper specific to an API enpoint we maintain.
The intention is to distribute this solution as nuget to other .NET teams that would need to consume the API endpoint.
Looking at the Autofac wire-up as a Module below - my question is would the consumer do this:
var client = PlayersAPIHttpClientModule("http:/api.players.com");
How does this setup facilitate the consumer to pass the base URI and then access the GetPlayerInformation method?
using Autofac;
using AutoMapper;
using Alpha.Domain.Players;
using System.Net.Http;
namespace Alpha.Clients.Players
{
public class PlayersAPIHttpClientModule : Module
{
private readonly string _serviceBaseUrl;
public PlayersAPIHttpClientModule(string serviceBaseUrl)
{
this._serviceBaseUrl = serviceBaseUrl;
}
protected override void Load(ContainerBuilder builder)
{
base.Load(builder);
builder.Register(ctx =>
{
var serviceClient = new HttpClient
{
BaseAddress =
new System.Uri(this._serviceBaseUrl)
};
return new
PlayerDomainManager(serviceClient,
ctx.Resolve<IMappingEngine>());
})
.SingleInstance()
.As<IPlayerDomainManager>();
}
}
}
This is the interface shared with the core domain.
public interface IPlayerDomainManager
{
IPlayer GetPlayerInformation (string playerId);
}
And this is the class itself with the exposed method functionality.
internal class PlayerDomainManager : IPlayerDomainManager
{
private readonly HttpClient _client;
private readonly IMappingEngine _mapper;
public PlayerDomainManager(HttpClient client, IMappingEngine mapper)
{
this._client = client;
this._mapper = mapper;
}
public IPlayer GetPlayerInformation(string playerId)
{
var response = this._client
.SendAsync
(new
HttpRequestMessage(HttpMethod.Get,
"/players/" + playerId),
CancellationToken.None)
.Result;
}
}

As described in the AutoFac Module documentation:
A module is a small class that can be used to bundle up a set of
related components behind a 'facade' to simplify configuration and
deployment. The module exposes a deliberate, restricted set of
configuration parameters that can vary independently of the components
used to implement the module.
As per the common use cases of Modules as described in the documentation, a common use case is to:
Configure related services that provide a subsystem, e.g. data access
with NHibernate
In the case of your code base, the PlayersAPIHttpClientModule is configuring the PlayerDomainManager as a service that implements the IPlayerDomainManager and configuring its lifetime to act as a singleton. The benefit is that the Module allows the deeply buried configuration requirement of the PlayerDomainManager (the base service url that in turn is required by one of its dependencies) to be surfaced as configuration centralised to the Modules constructor. This benefit would be more obvious if the configuration was more complex.
Modules need to be registered with AutoFac as per any other dependency:
builder.RegisterModule(new PlayersAPIHttpClientModule("base_service_url));
In turn, the services they configure are resolved using standard AutoFac dependency resolution.
scope.Resolve<IDomainPlayerManager>();
So, to answer your question, no you would not use the PlayersAPIHttpClientModule as per your question.
Register the PlayersAPIHttpClientModule with the AutoFac ContainerBuilder
Use the AutoFac Container to resolve the IDomainPlayerManager as required

Related

Using StructureMap[4.7.0] Setter Injection in my MVC5 Controller

I am trying to inject the IApplicationConfigurationSection implementation into this MVC5 Controller, so that I can have access to some of the information (various strings) from my web.config custom section in all of my views:
public class BaseController : Controller
{
public IApplicationConfigurationSection AppConfig { get; set; }
public BaseController()
{
ViewBag.AppConfig = AppConfig; // AppConfig is always null
}
}
I want to use setter injection so I don't have to clutter up my derived Controller constructors with parameters that they don't really care about.
Note: If there is a better way to inject base class dependencies, please let me know. I admit I may not be on the right track here.
In my Global.asax I load my StructureMap configurations:
private static IContainer _container;
protected void Application_Start()
{
_container = new Container();
StructureMapConfig.Configure(_container, () => Container ?? _container);
// redacted other registrations
}
My StructureMapConfig class loads my registries:
public class StructureMapConfig
{
public static void Configure(IContainer container, Func<IContainer> func)
{
DependencyResolver.SetResolver(new StructureMapDependencyResolver(func));
container.Configure(cfg =>
{
cfg.AddRegistries(new Registry[]
{
new MvcRegistry(),
// other registries redacted
});
});
}
}
My MvcRegistry provides the mapping for StructureMap:
public class MvcRegistry : Registry
{
public MvcRegistry()
{
For<BundleCollection>().Use(BundleTable.Bundles);
For<RouteCollection>().Use(RouteTable.Routes);
For<IPrincipal>().Use(() => HttpContext.Current.User);
For<IIdentity>().Use(() => HttpContext.Current.User.Identity);
For<ICurrentUser>().Use<CurrentUser>();
For<HttpSessionStateBase>()
.Use(() => new HttpSessionStateWrapper(HttpContext.Current.Session));
For<HttpContextBase>()
.Use(() => new HttpContextWrapper(HttpContext.Current));
For<HttpServerUtilityBase>()
.Use(() => new HttpServerUtilityWrapper(HttpContext.Current.Server));
For<IApplicationConfigurationSection>()
.Use(GetConfig());
Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());
}
private IApplicationConfigurationSection GetConfig()
{
var config = ConfigurationManager.GetSection("application") as ApplicationConfigurationSection;
return config; // this always returns a valid instance
}
}
I have also "thrown my hands up" and tried using the [SetterProperty] attribute on the BaseController - that technique failed as well.
Despite my best efforts to find a solution, the AppConfig property in my controller's constructor is always null. I thought that
`Policies.SetAllProperties(p => p.OfType<IApplicationConfigurationSection>());`
would do the trick, but it didn't.
I have found that if I discard setter injection and go with constructor injection, it works as advertised. I'd still like to know where I'm going wrong, but I'd like to stress that I'm not a StructureMap guru - there may be a better way to avoid having to constructor-inject my base class dependencies. If you know how I should be doing this but am not, please share.
While constructor injection in this scenario appears to be the better solution to the stated problem as it follows The Explicit Dependencies Principle
Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.
The mention of only needing to access the AppConfig in your views leads me to think that this is more of an XY problem and a cross cutting concern.
It appears that the controllers themselves have no need to use the dependency so stands to reason that there is no need to be injecting them into the controller explicitly just so that the dependency is available to the View.
Consider using an action filter that can resolve the dependency and make it available to the View via the same ViewBag as the request goes through the pipeline.
public class AccessesAppConfigAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
var resolver = DependencyResolver.Current;
var appConfig = (IApplicationConfigurationSection)resolver.GetService(typeof(IApplicationConfigurationSection));
filterContext.Controller.ViewBag.AppConfig = appConfig;
}
}
This now makes the required information available to the views with out tight coupling of the controllers that may have a use for it. Removing the need to inject the dependency into derived classes.
Either via adorning Controller/Action with the filter attribute
[AccessesAppConfig] //available to all its actions
public class HomeController : Controller {
//[AccessesAppConfig] //Use directly if want to isolate to single action/view
public ActionResult Index() {
//...
return View();
}
}
or globally for all requests.
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new AccessesAppConfigAttribute());
}
}
At this point it really does not matter which IoC container is used. Once the dependency resolver has been configured, Views should have access to the required information in the ViewBag

How to handle 3rd Party assembly internally calling AutoMapper Initialize

I make use of a 3rd party DLL which internally uses AutoMapper and initializes it with AutoMapper.Initialize() but then from what I understand, I cannot also call Initialize() as it clear existing maps.
What is the best solution for a 3rd party to use AutoMapper without conflicting with my own code?
Or another way.. how should a shared assembly set itself up with AutoMapper which guarantees it's own profiles are initializes but allows the consumer of that assembly to initialize it's own profiles?
Should the 3rd party assembly just define it's profiles and rely on the calling code to initialize all enabled profiles - manually adding profiles from the 3rd part assembly?
I am using AutoMapper 5.1 at the moment.
The best way to do this is not to use the static instance of Mapper - create your own, and use Dependency Injection to inject an instance of IMapper wherever you need to use AutoMapper. This also makes it a lot easier to test your code.
This is how I do things using autofac as my DI container:
builder.Register<IMapper>(c =>
{
var profiles = c.Resolve<IEnumerable<Profile>>();
var config = new MapperConfiguration(cfg =>
{
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
return config.CreateMapper();
}).SingleInstance();
This way, whenever I need to use automapper, I just add it to my constructor:
public class MyClass
{
private readonly IMapper _mapper;
public MyClass(IMapper mapper)
{
_mapper = mapper;
}
public void DoSomething()
{
var mapped = _mapper.Map<Dto>(....);
}
}

Approach on mocking ServiceStack service being called by another ServiceStack service

Let's say we have a situation where a service would call other services in ServiceStack.
From reading around, this is how one would call another service:
public class CompanyService : Service
{
public SetupCompanyResponse Any(SetupCompany request)
{
var employeeService = base.ResolveService<EmployeeService>();
// Do something with employeeService
var response = employeeService.Any(new SetupEmployees());
return new SetupCompanyResponse { NumOfEmployeesCreated = response.Count };
}
}
Question: How do I mock EmployeeService if I'm unit-testing CompanyService?
Easiest way I could think of is to generate an IEmployeeService interface so that it's easily mockable. However I'm not sure if base.ResolveService<T> will be able to properly resolve and auto-wire a ServiceStack service, given its interface instead, like so:
var employeeService = base.ResolveService<IEmployeeService>();
Especially when we are registering services this way (which I assume is configuring the object resolution based on concrete class, and not the interface e.g IEmployeeService)
public HelloAppHost() : base("Hello Web Services", typeof(HelloService).Assembly) { }
Update:
Apparently I'm able to somewhat achieve this simply by:
1) Registering the service interface with its implementation
public static void SetupServices(Container container)
{
container.RegisterAs<EmployeeService, IEmployeeService>();
}
2) Using the same exact code to resolve, except now I pass in the interface. The service is successfully resolved.
var employeeService = base.ResolveService<IEmployeeService>();
3) All I need to do now is to override the resolver, and the service dependency should be totally mockable.
Question: Is this also a valid approach? Why or why not?
ServiceStack's Service class resolves all its dependencies from an IResolver, defined by:
public interface IResolver
{
T TryResolve<T>();
}
This can be injected in ServiceStack's Service class in an number of ways as seen by the implementation:
public class Service : IService, IServiceBase, IDisposable
{
public static IResolver GlobalResolver { get; set; }
private IResolver resolver;
public virtual IResolver GetResolver()
{
return resolver ?? GlobalResolver;
}
public virtual Service SetResolver(IResolver resolver)
{
this.resolver = resolver;
return this;
}
public virtual T TryResolve<T>()
{
return this.GetResolver() == null
? default(T)
: this.GetResolver().TryResolve<T>();
}
...
}
Which you can use to control how Services resolve dependencies.
An easy way to unit test Services is to use a BasicAppHost as seen on the Testing wiki, i.e:
appHost = new BasicAppHost().Init();
var container = appHost.Container;
container.Register<IDbConnectionFactory>(
new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
container.RegisterAutoWired<CompanyService>();
container.RegisterAutoWiredAs<StubEmployeeService, EmployeeService>();
Where StubEmployeeService is your stub implementation of EmployeeService, e.g:
public class StubEmployeeService : EmployeeService
{
public SetupEmployeesResponse Any(SetupEmployees request)
{
return new SetupEmployeesResponse { ... };
}
}
You can also register Services using any of the registration methods ServiceStack's IOC Supports if you prefer to use your own mocking library.

ServiceStack Access Ioc container within Custom CredentialsAuthProvider

I've extended the CredentialsAuthProvider provided by service-stack to allow me to authenticate against a Active-Directory instance. The AD access logic is encapsulated within a custom class called AdManager (see below)
e.g.:
public class AdCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService,
string userName,
string password)
{
IAdManager manager = new AdManager();
return manager.Authenticate(userName, password);
}
...
Question:
I was hoping I could register the AdManager using service-stacks built-in IoC "Funq.Container" within my extended "AppHostBase" and access it from within my custom CredentialsAuthProvider? I tried registering it but have not found a way of accessing the IoC (or my registered AdManager object) via the service-stack built in framework.
Am I missing something?
Thanks
You can access the IOC from within the AuthProvider with the supplied IServiceBase, e.g:
var addManager = authService.TryResolve<IAdManager>();
Anywhere else you can always resolve dependencies using the Singleton:
var addManager = HostContext.TryResolve<IAdManager>();
Otherwise if you know it's in an ASP.NET Web Host you also access it via your AppHost singleton:
var addManager = AppHostBase.Instance.Resolve<IAdManager>();
Service Stack uses property injection as well. I have used property injection when extending the Service class provided by Service stack.
public class MyService : Service
{
public MyService(IDb db)
{
//db constructor inject
}
public IValidator<MyData> MyDataValidator { get; set; }
public object Get(MyData request)
{
//MyDataValidator is property injected
}
}
I believe the same logic can be applied to the AuthProvider. But I havent tested it.

ServiceStack - Empty Request Classes?

I have a question regarding ServiceStack. Why are there empty Request Classes, why do we have to have a Request Class? For example:
[Route("/test", "GET")]
public class Test
{
}
public class TestResponse
{
public string Date { get; set; }
}
public class TestService : Service
{
public object Get(Test test)
{
return new TestResponse { Date = DateTime.Now.ToString() };
}
}
If I don't pass an object with my request, my service fails?
Then I'm my Global.asax file, I have:
public class AxDataAppHost : AppHostBase
{
public AxDataAppHost() :
base("AxData", typeof(TestService).Assembly)
{
}
}
What if I have more than 1 service, in the example above I'm using TestService but what if I have one for Customers, Orders and Products? How do I handle multiple services?
why do we have to have a Request Class?
ServiceStack is a message-based framework that embraces Martin Fowler's Remote Service Best Practices (i.e. Remote Facade, DTOs and Gateway) which utilizes a ServiceGateway to send coarse-grained Request DTOs which commonly returns a typed Response DTO (though services can return anything). Using a message-based design has many advantages and is what enables ServiceStack's typed end-to-end API.
E.g. you can re-use these types you defined your services with:
public class Test : IReturn<TestResponse> {}
public class TestResponse
{
public string Date { get; set; }
}
On the client, which is what gives you a typed API without code-gen, e.g:
var client = new JsonServiceClient(BaseUri);
TestResponse response = client.Get(new Test());
Note: you don't even need custom routes as by default ServiceStack's C# clients will fallback to use the pre-defined routes (enabled by default).
What if I have more than 1 service, in the example above I'm using TestService but what if I have one for Customers, Orders and Products? How do I handle multiple services?
In your AppHost base constructor you're passing in an assembly (i.e. NOT a single service):
public AxDataAppHost() : base("AxData", typeof(TestService).Assembly) {}
This tells ServiceStack where to look for and wire-up all your services. You only need to do this once for each dll/assembly that your services are in.
ServiceStack's AppHosts also allows specifying multiple assemblies which you can use to wire-up services located in multiple assemblies, e.g:
public AxDataAppHost()
: base("AxData", typeof(TestService).Assembly, typeof(ServiceInNewDll).Assembly) {}

Resources