RegisterMultiple does not keep implementation type as singleton if registered as multiple registration types? - nancy

I am trying to add a type called TypeA as two different registration types: InterfaceA and InterfaceB.
container.RegisterMultiple(typeof(InterfaceA), new[] {typeof(TypeA), typeof(TypeB)});
container.RegisterMultiple(typeof(InterfaceB), new[] {typeof(TypeA), typeof(TypeC)});
But when I Resolve them, I get one instance of TypeA when resolving InterfaceA, and another instance when resolving InterfaceB. I expect to get the same instance for both resolves, but I am not.
I have also tried to add .AsSingleton() to the call, but it made no difference.
Am I doing something wrong, or does anyone have any ideas of doing this without adding a TypeAFactory or such that keeps track of the instances instead?
Thanks in advance for any help.

I think what you are seeing is by design.
To get the same instance for both interfaces you can create the instance yourself and register it for both interfaces:
var instanceOfA = new TypeA(...);
container.Register<InterfaceA>(instanceOfA);
container.Register<InterfaceB>(instanceOfA);

I solved this on my own with a quite ugly (but yet quite elegant) solution.
I create another, internal, instance of a TinyIoCContainer, and I register all my types with the actual TinyIoCContainer.Current by giving it a factory in the form of:
var container = TinyIoCContainer.Current;
var internalIoC = new TinyIoCContainer();
Dictionary<Type, Object> instances = new Dictionary<Type, Object>();
...
Func<TinyIoCContainer, NamedParameterOverloads, Object> factory = (TinyIoCContainer c, NamedParameterOverloads o) =>
{
if (instances.ContainsKey(implementationType) == false)
{
// Create the instance only once, and save it to our dictionary.
// This way we can get singleton implementations of multi-registered types.
instances.Add(implementationType, internalIoC.Resolve(implementationType));
}
return instances[implementationType];
};
container.Register(registerType, factory, implementationType.FullName);
I'm sure there will be a few caveats with this solution, but I'm also sure I'll be able to figure out a workable fix for them, as things look right now.

Related

How to create a read-only array in java?

I want to get rid of clone() method.
For the below class sonar (static code check tool) was complaining that
I should not directly expose an internal array of the object as one can change the array after the method call which in turn changes the object's state. It suggested to do a clone() of that array before returning so that object's state is not changed.
Below is my class...
class DevicePlatformAggregator implements IPlatformListings{
private DevicePlatform[] platforms = null;
public DevicePlatform[] getAllPlatforms() throws DevicePlatformNotFoundException {
if (null != platforms) {
return platforms.clone();
}
List<DevicePlatform> platformlist = new ArrayList<DevicePlatform>();
..... // code that populates platformlist
platforms = platformlist.toArray(new DevicePlatform[platformlist.size()]);
return platforms;
}
}
However I don't think its good to clone as its unnecessary to duplicate the data.
There is nothing similar to Collections.unmodifiableList() for array
I can not change the return type of the method getAllPlatforms() to some
collection as it is an interface method
I am not a Java guru but I am pretty confident that you are out of luck here. There is no way to make a primitive array immutable apart from creating an array of 0 elements.
Making it final won't help cause only the reference pointing to it would be immutable.
As you already said the way to go in obtaining an unmodifiable list would be to use Collections as in the following example:
List<Integer> contentcannotbemodified= Collections.unmodifiableList(Arrays.asList(13,1,8,6));
Hope it helps.

New to AutoFixture trying to get my head around it and I can't see it helping me

Currently, I'm using custom made fake objects that behind the scenes use NSubstitute which creates the actual objects but it's becoming very hard to maintain as the project grows, so I'm trying to find alternatives and I'm hoping that AutoFixture is the right tool for the job.
I read the documentation and I'm struggling because there's very little to no documentation and I read most of the blog posts by Mark Seemann including the CheatSheet.
One of the things that I'm having hard time to grasp is how to create an object with a constructor that have parameters, in my case I need to pass argument to CsEmbeddedRazorViewEngine as well as HttpRequestBase to ControllerContext.
The way I see it is that I need to create a fake objects and finally create a customization object that injects them to
I also looked into NBuilder it seems slightly more trivial to pass arguments there but I've heard good things about AutoFixture and I would like to give it a try. :)
I'm trying to reduce the amount of fake objects I have so here is a real test, how can I do the same thing with AutoFixture?
[Theory,
InlineData("en-US"),
InlineData("en-us"),
InlineData("en")]
public void Should_return_the_default_path_of_the_view_for_enUS(string language)
{
// Arrange
const string EXPECTED_VIEW_PATH = "~/MyAssemblyName/Views/Home/Index.cshtml";
CsEmbeddedRazorViewEngine engine = CsEmbeddedRazorViewEngineFactory.Create(ASSEMBLY_NAME, VIEW_PATH, string.Empty);
string[] userLanguage = { language };
HttpRequestBase request = FakeHttpRequestFactory.Create(userLanguage);
ControllerContext controllerContext = FakeControllerContextFactory.Create(request);
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, VIEW_NAME, false);
// Assert
RazorView razorView = (RazorView)result.View;
string actualViewPath = razorView.ViewPath;
actualViewPath.Should().Be(EXPECTED_VIEW_PATH);
}
P.S. I'm using xUnit as my testing framework and NSubstitute as my mocking framework should I install both AutoFixture.Xunit and AutoFixture.AutoNSubstitute?
UPDATE: After learning more and more about it I guess it is not the right tool for the job because I tried to replace my test doubles factories with AutoFixture rather than setting up my SUT with it.
Due to odd reason I thought it's doing the same thing NBuilder is doing and from what I can see they are very different tools.
So after some thinking I think I'll go and change the methods I have on my test doubles factories to objects then use AutoFixture to create my SUT and inject my test doubles to it.
Note: I don't have the source code for the CsEmbeddedRazorViewEngine type and all the other custom types.
Here is how it could be written with AutoFixture:
[Theory]
[InlineAutoWebData("en-US", "about", "~/MyAssemblyName/Views/Home/Index.cshtml")]
[InlineAutoWebData("en-US", "other", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view_for_enUS(
string language,
string viewName,
string expected,
ControllerContext controllerContext,
CsEmbeddedRazorViewEngine sut)
{
var result = sut.FindPartialView(controllerContext, viewName, false);
var actual = ((RazorView)result.View).ViewPath;
actual.Should().Be(expected);
}
How it works:
It uses AutoFixture itself together with it's glue libraries for xUnit.net and NSubstitute:
PM> Install-Package AutoFixture.Xunit
PM> Install-Package AutoFixture.AutoNSubstitute
With InlineAutoWebData you actually combine inline values and auto-generated data values by AutoFixture – also including Auto-Mocking with NSubstitute.
internal class InlineAutoWebDataAttribute : CompositeDataAttribute
{
internal InlineAutoWebDataAttribute(params object[] values)
: base(
new InlineDataAttribute(values),
new CompositeDataAttribute(
new AutoDataAttribute(
new Fixture().Customize(
new WebModelCustomization()))))
{
}
}
Remarks:
You could actually replace the WebModelCustomization customization above with AutoNSubstituteCustomization and it could work.
However, assuming that you are using ASP.NET MVC 4, you need to customize the Fixture instance with:
internal class WebModelCustomization : CompositeCustomization
{
internal WebModelCustomization()
: base(
new MvcCustomization(),
new AutoNSubstituteCustomization())
{
}
private class MvcCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<ControllerContext>(c => c
.Without(x => x.DisplayMode));
// Customize the CsEmbeddedRazorViewEngine type here.
}
}
}
Further reading:
Encapsulating AutoFixture Customizations
AutoData Theories with AutoFixture
I ended up doing this.
[Theory,
InlineData("en-US", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en-us", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view(string language, string viewName, string expected)
{
// Arrange
CsEmbeddedRazorViewEngine engine = new CsEmbeddedRazorViewEngineFixture();
ControllerContext controllerContext = FakeControllerContextBuilder.WithLanguage(language).Build();
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, viewName, false);
// Assert
string actualViewPath = ((RazorView)result.View).ViewPath;
actualViewPath.Should().Be(expected);
}
I encapsulated the details to setup my SUT into a fixture and used the builder pattern to handle my fakes, I think that it's readable and pretty straightforward now.
While AutoFixture looks pretty cool, the learning curve seems long and I will need to invest enough time to understand it, for now, I want to clean-up my unit tests and make them more readable. :)

How can I return a Dictionary<string, Object> as JsonResult, AND get the proper result in JavaScript?

I'm constructing my JsonResult in Controller by adding some extra information to an already existing JsonResult (returned from a different method). In order to add more properties, I converted the initial JsonResult into a Dictionary:
IDictionary<string, object> wrapper = (IDictionary<string, object>)new
System.Web.Routing.RouteValueDictionary(json.Data);
Then I just add data by writing wrapper["..."] = "value".
The method returns a new JsonResult, with wrapper as .Data:
new JsonResult() { wrapper, JsonRequestBehavior.AllowGet };
and that's where the troubles start; while communication happens perfectly, and the success function gets called, the resulting array which I use in JavaScript doesn't have the clean structure I expect: instead of accessing values as val = ret.PropName1; I end up having to access a simple indexed array, which contains in turn a dictionary with two pairs: { "Value"="val, "Key"="PropName1" }; (so something like o[0].Key would give me the property name)
I'd like to know if there's a smart, fast way to rewrite the JsonResult creation in the Controller, to get a nice clean dictionary in the View.
There are a couple of ideas I have, but they aren't particularly clean: I could throw away JsonResult reuse on the server side, and just make an anonymous object with all the right properties; or, I could make a translation function in Javascript which could translate the result into a new Array(). I'm looking for better solutions.
[Later Edit] The array comes the way it does because the dictionary was defined as <string, object>. If it were <string, string>, it would be sent the way I'd originally expect it. But since I actually use objects from that bag, I'll just leave it the way it is, and pass the json response through the below function.
Addendum: while writing the above question, it occurred to me that the translation between 'bad' array and 'good' array is indeed very simple:
function translateAjaxResult(ret) {
var result = new Array();
if (ret == null) return result;
for(var i = 0; i < ret.length; i++)
result[ret[i].Key] = ret[i].Value;
return result;
}
Nonetheless, it's still a patch to a problem and not a fix to a problem, so I'd still like a more elegant solution.

Creating Test EntityList objects - RIA Services

I'm creating an EnityList to do some client side testing with my ViewModel. Something like:
var people = new EntityList<Person>()
{
new Incident() {Age = 55, Name="Joe"},
new Incident() {Age=42, Name="Sam"}
};
The problem is that the implicit (and explicit) Adds fail. The entitylist is created as read-only. Any thoughts on how to create a test EntityList?
If you're doing testing then you probably don't want an EntityList. I would expect that a ViewModel shouldn't know about the EntityList, but rather should just get access to an IEnumberable instead. Both EntityList and List expose this, so in your tests you can just create a List.
I realize this doesn't help with the issue of EntityList being read-only. :)
I think you also need an EntityContainer to own your EntityList.

Can someone explain the magic going on in Prism's resolve<> method?

I've got a CustomersModule.cs with the following Initialize() method:
public void Initialize()
{
container.RegisterType<ICustomersRepository, CustomersRepository>(new ContainerControlledLifetimeManager());
CustomersPresenter customersPresenter = this.container.Resolve<CustomersPresenter>();
}
The class I resolve from the container looks like this:
class CustomersPresenter
{
private CustomersView view;
private ICustomersRepository customersRespository;
public CustomersPresenter(CustomersView view,
ICustomersRepository customersRepository,
TestWhatever testWhatever)
{
this.view = view;
this.customersRespository = customersRepository;
}
}
The TestWhatever class is just a dummy class I created:
public class TestWhatever
{
public string Title { get; set; }
public TestWhatever()
{
Title = "this is the title";
}
}
Yet the container happily resolves CustomersPresenter even though I never registered it, and also the container somehow finds TestWhatever, instantiates it, and injects it into CustomersPresenter.
I was quite surprised to realize this since I couldn't find anywhere in the Prism documentation which explicitly stated that the container was so automatic.
So this is great, but it what else is the container doing that I don't know about i.e. what else can it do that I don't know about? For example, can I inject classes from other modules and if the modules happen to be loaded the container will inject them, and if not, it will inject a null?
There is nothing magical going on. You are specifying concrete types, so naturally they are resolvable, because if we have the Type object, we can call a constructor on it.
class Fred { };
Fred f1 = new Fred();
Type t = typeof(Fred);
Fred f2 = (Fred)t.GetConstructor(Type.EmptyTypes).Invoke(null);
The last line above is effectively what happens, the type t having been found by using typeof on the type parameter you give to Resolve.
If the type cannot be constructed by new (because it's in some unknown separate codebase) then you wouldn't be able to give it as a type parameter to Resolve.
In the second case, it is constructor injection, but it's still a known concrete constructable type. Via reflection, the Unity framework can get an array of all the Types of the parameters to the constructor. The type TestWhatever is constructable, so there is no ambiguity or difficulty over what to construct.
As to your concern about separate modules (assemblies), if you move TestWhatever to another assembly, that will not change the lines of code you've written; it will just mean that you have to add a reference to the other assembly to get this one to build. And then TestWhatever is still an unambiguously refeferenced constructable type, so it can be constructed by Unity.
In other words, if you can refer to the type in code, you can get a Type object, and so at runtime it will be directly constructable.
Response to comment:
If you delete the class TestWhatever, you will get a compile-time error, because you refer to that type in your code. So it won't be possible to get a runtime by doing that.
The decoupling is still in effect in this arrangement, because you could register a specific instance of TestWhatever, so every call to Resolve<TestWhatever>() will get the same instance, rather than constructing a new one.
The reason this works is because Unity is designed for it. When you Resolve with a concrete type, Unity looks to see if it can resolve from the container. If it cannot, then it just goes and instantiates the type resolving it's dependencies. It's really quite simple.

Resources