Create AutoMapper in Test Project (including AutoMapper.Profile classes) - automapper

I have a .net core service api which uses AutoMapper, and in Startup::ConfigureServices the services collection uses the AddAutoMapper extension to perform all the initialization necessary for dependency injection of an IMapper interface, e.g. services.AddAutoMapper(typeof(Startup)); The way I understand it is that by doing this, scanning is done for any/all AutoMapper.Profile types in order to set up the IMapper for DI into other constructors. Works great.
Now I'm writing tests for the service, and am wondering how to create this IMapper outside of Startup? Mocking it seems pointless, I just want to use it, so how do I create an instance of what I need that utilizes all of the AutoMapper.Profiles I have set up?

I was able to get this working by simply creating a MapperConfiguration which points to the needed Profile classes:
var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile<TestProfile>());
IMapper _mapper = new Mapper(mapperConfig);

Related

DocuSign - Is there a better way to instantiate the APIclient using the C# sdk in .net core?

I am using E-signature C# SDK to integrate with DocuSign Api's from my .NET6 based API. As per the documentation ApiClient is instantiated like var client = new ApiClient("base address") .
Is there way to use the middleware to create an instance of the ApiClient so that I can only instantiate it once and inject it in my class, to call the SDK methods.
There are multiple constructors you can use.
You can just do new ApiClient() which defaults the basePath to be https://www.docusign.net/restapi
You can also use a Configuration object and pass that to the constructor instead of a basePath.
The most advanced constructor is this:
public ApiClient(string basePath, string oAuthBasePath, WebProxy proxy = null)
This one allows you to specify a different oAuthBasePath and even a WebProxy should you need one.
However, I assume you're actually asking about using dependency injection so that you can have your controllers pass along the singleton.
As it stands right now ApiClient is not implementing any Interface, so you cannot do it directly.
You can create your own class that extends ApiClient, implements some new interface you provide and then you'll be able to get this capability.
You can also take the code for the C# SDK and modify it to be an interface (IApiClient would probably be the name you want to use)

Pluggable service assemblies. How to add list of assemblies without hardcoding tem in the AppHost constructor

I have question about how to make service assemblies pluggable (read them from config file) into the ServiceStack.
I want to register my services assemblies from configuration file and not to hard code them in the AppHost constructor like this:
public appHost() : base("My Pluggable Web Services", typeof(ServiceAssembly1).Assembly, typeof(AnotherServiceAssembly).Assembly) { }
I couldn't find other way to register the assemblies outside of this constructor. The constructor also accepts params and does not have overload for example with IEnumerable<Assembly> as parameter.
The idea is to be able to plug service assemblies without touching the service stack REST web site.
I looked at the Plugin interface but I think it is more suitable to be used to extend the service stack not to dynamically plug service assemblies.
Are there any way to implement such pluggable service assemblies feature with the current service stack release? Can you also add constructor overload that will accept the array of assembly?
Thank you in advance
The purpose of your ServiceStack's AppHost is to be a bespoke class customized for your solution that has hard references to all your service dependencies. It's much easier to verify your application is configured correctly, at build time if you declare your dependencies in code as opposed to un-typed configuration.
Having said that you can override the strategy that ServiceStack uses to discover your Service types by overriding AppHostBase.CreateServiceManager():
protected virtual ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
{
return new ServiceManager(assembliesWithServices);
//Alternative way to inject Container + Service Resolver strategy
//return new ServiceManager(new Container(),
// new ServiceController(() => assembliesWithServices.ToList().SelectMany(x => x.GetTypes())));
}
Otherwise you can still do what you want by just passing your assemblies into your AppHost, e.g:
var appHost = new AppHost("Service Name", MyConfig.LoadAssembliesFromConfig());
(new AppHost()).Init();

Mocking Azure RoleEnvironment API with Microsoft Fakes

I'm trying to mock the Azure RoleEnvironment API with Microsoft Fakes. The problem is that I can't find a way to arrange the shims/stubs so that I can exercise the code in a unit test.
For instance, suppose I have the following code:
using Microsoft.WindowsAzure.ServiceRuntime;
// ...
Role role = RoleEnvironment.CurrentRoleInstance.Role;
int count = role.Instances.Count;
How would I mock the above with Fakes so that I can run it in a unit test?
So far my attempts fail because the RoleInstance class appears to have abstract properties with internal setters which prevents me from deriving a class from RoleInstance. This in turn prevents me from providing a shim for RoleEnvironment.CurrentRoleInstance.
BTW, I'm fully aware that relying too much on Fakes can be considered harmful. The thing is, I already have a wrapper for RoleEnvironment, together with production and test implementations. The code I'm trying to mock is in the production implementation which I want to test as well.
Unfortunately, I don't believe it is possible to isolate this code with Microsoft Fakes today. Normally, you would want to shim the RoleEnvironment.CurrentRoleInstance property to return a stub RoleInstance, that returns a stub Role. We can shim the CurrentRoleInstance property. But as you pointed out, both RoleInstance and Role are abstract classes with internal constructors, which we cannot stub with the current version of Fakes.

Can ACS Service Namespace creation be automated?

First, let me state my real problem: I've got code that makes calls to the ACS Management service, and I'd like my integration tests to be able to be run concurrently without each test run clobbering the others. That is, since multiple people / build servers might end up running these tests concurrently, if they're all using the same ACS service namespace, concurrency issues arise.
My thinking is the simplest means of achieving this would be to generate new, unique ACS service namespaces for each test runner -- but as far as I can tell, there's no automated way of creating new service namespaces (or management client keys). Am I wrong? Is there another way of going about this?
An automated method of creating new service namespaces would be extraordinarily helpful.
You are correct. That's not possible today. Maybe you can describe your scenario in more detail and there might be some alternative solutions to avoid having to recreate the namespace?
Technically it should be possible, since the Management Portal is a Silverlight application accessing a WCF RIA Service.
If you dig deep enough you'll find some useful information:
This is the Silverlight XAP for the management of Windows Azure AppFabric: https://appfabricportal.windows.azure.com/ClientBin/Microsoft.AppFabric.WebConsole.4.1.3.xap
This is the service being used when listing/creating/... namespaces etc..: https://appfabricportal.windows.azure.com/Services/Microsoft-AppFabric-Web-Services-AppFabricDomainService.svc?wsdl
And this is a piece of the DomainContext:
public sealed class AppFabricDomainContext : DomainContext
{
public AppFabricDomainContext(Uri serviceUri)
: this((DomainClient) new WebDomainClient<AppFabricDomainContext.IAppFabricDomainServiceContract>(serviceUri, true))
{
}
...
public InvokeOperation CreateServiceNamespace(IEnumerable<string> serviceNames, string parentProjectKey, string serviceNamespace, IEnumerable<string> packageKeys, string regionKey, Action<InvokeOperation> callback, object userState)
{
Dictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("serviceNames", (object) serviceNames);
dictionary.Add("parentProjectKey", (object) parentProjectKey);
dictionary.Add("serviceNamespace", (object) serviceNamespace);
dictionary.Add("packageKeys", (object) packageKeys);
dictionary.Add("regionKey", (object) regionKey);
this.ValidateMethod("CreateServiceNamespace", (IDictionary<string, object>) dictionary);
return this.InvokeOperation("CreateServiceNamespace", typeof (void), (IDictionary<string, object>) dictionary, true, callback, userState);
}
}
Finding this info was the easy part, getting it to work... that's something else. Take the authentication part for example, you'll need to authenticate with Windows Live and use those credentials when calling the WCF RIA Service.
Good luck!

WCF Service hosted by IIS 7 and global variables ( singletons )

In my case I am using Lucene.Net for search and would like to use single instances of IndexReader and IndexSearcher. Where should I move them from a method to be able just to instantiate once for the first query and then reuse.
public static List<MyType> GetIndexMatches(string fullTextIndexPath, string keyWord )
{
IndexSearcher searcher = null;
IndexReader reader = null;
try
{
searcher = new IndexSearcher(fullTextIndexPath);
reader = IndexReader.Open(fullTextIndexPath);
...
Have you tried making them static that exists at the Service level (not at the web method level)?
I am not sure if you are familiar with IoC (Inversion of Control), but if you use a container like Castle Windsor or Ninject 2 (both of these integrate well with WCF, and can take over the creation of WCF service instances through the container), you can configure some injectable dependencies for your IndexSearcher and IndexReader. When defining such a component, you can give them a "lifestyle" of singleton. The benefit of using an IoC container is that you can inject the same component instances into any dependent class that needs them, and easily reuse your singleton components across an entire application with ease.
Castle Windsor
Ninject 2

Resources