Turn off "builders" in MapStruct when using Immutables - mapstruct

How do I completely disable using "builders" in MapStruct? I don't want to use them at all as they are causing all kinds of issues for me.
I created the service file under META-INF (I would prefer a way to assign it to the mapping builder= but I did not see any examples how to do it right in code).
It is still trying to use Immutables "builder" instance instance of the "ModifiableXXX" instance I want to map to. I'd even take a way of forcing it to the modifiable type if that is available.
In another mapping, using an update the ModifiableXXX (with #AfterMapping and #MappingTarget) approach works.
My mapper looks like this right now:
#Mapper
public interface MongoProjectMapper
{
ModifiableProject mapModel(MongoProject project);
#AfterMapping
ModifiableProject updateProject(MongoEntity e, #MappingTarget ModifiableProject p);
}

From Mapstruct version 1.3.1.Final we can use annotation org.mapstruct.Builder#disableBuilder within: #BeanMapping, #Mapper or #MapperConfig
#Mapper(builder = #Builder(disableBuilder = true))
public interface ProjectMapper
Have a look at #mapping-with-builders and documentation

Completely disabling builders is possible via the NoOpBuilderProvider. You need to create a org.mapstruct.ap.spi.BuilderProvider file in the META-INF/services directory with org.mapstruct.ap.spi.NoOpBuilderProvider as it’s content. This will completely disable the builders.
There is a feature request to make this more granular and disable it via #BeanMapping or on the mapper level. Have a look at mapstruct/mapstruct#1661

Related

IOC vs New guidelines

Recently I was looking at some source code provided by community leaders in their open source implementations. One these projects made use of IOC. Here is sample hypothetical code:
public class Class1
{
private ISomeInterface _someObject;
public Class1(ISomeInterface someObject)
{
_someObject = someObject;
}
// some more code and then
var someOtherObject = new SomeOtherObject();
}
My question is not about what the IOCs are for and how to use them in technical terms but rather what are the guidelines regarding object creation. All that effort and then this line using "new" operator. I don't quite understand. Which object should be created by IOC and for which ones it is permissible to be created via the new operator?
As a general rule of thumb, if something is providing a service which may want to be replaced either for testing or to use a different implementation (e.g. different authentication services) then inject the dependency. If it's something like a collection, or a simple data object which isn't providing behaviour which you'd ever want to vary, then it's fine to instantiate it within the class.
Usually you use IoC because:
A dependency that can change in the future
To code against interfaces, not concrete types
To enable mocking these dependencies in Unit Testing scenarios
You could avoid using IoC in the case where you don't control the dependency, for example an StringBuilder is always going to be an StringBuilder and have a defined behavior, and you usually don't really need to mock that; while you might want to mock an HttpRequestBase, because it's an external dependency on having an internet connection, for example, which is a problem during unit tests (longer execution times, and it's something out of your control).
The same happens for database access repositories and so on.

GWT: Replace AbstractPlaceHistoryMapper with a custom mapper using deferred binding

Looks like the class that is generated for PlaceHistoryMapper is hard-coded to use AbstractPlaceHistoryMapper as the super class.
So, I am trying to work around this by trying to replace this AbstractPlaceHistoryMapper with a custom mapper of mine using deferred binding . I am using the following rule in my *.gwt.xml:
<replace-with class="com.google.gwt.place.impl.AbstractPlaceHistoryMapper">
<when-type-is class="com.test.sampleapp.CustomPlaceHistoryMapper" />
</replace-with>
But for some reason the replace does not seem to be happening. CustomPlaceHistoryMapper is not getting kicked in and the generated class still uses AbstractPlaceHistoryMapper.
Any thoughts/pointers as to what might be resulting this behavior are much appreciated.
Note: I have also posted this on the GWT group but haven't received an answer so far.
To make the deferred binding work a class must be created with GWT.create(). However, AbstractPlaceHistoryMapper is only used as an extended class. So it will never be created via GWT.create, but always by instantiation the subclass. And therefor deferred binding won't work in this case. If you want a complete different implementation you have to implement a custom PlaceHistoryMapper, and manage the known tokens yourself. This also means you can't use the History annotations either.
As a side note the classnames in your rule should be swapped. But for the end result this doesn't matter, since it won't work in the first place.
It is absolutely possible to have custom history tokens (eg. #mail or #mail/bla instead of only #mail:inbox) using the out-of-the-box Place-related classes that GWT (2.0) provides.
Instead of replacing AbstractPlaceHistoryMapper you could instantiate the default PlaceHistoryMapper passing in it's constructor your implementation of PlaceHistoryMapper<T> or PlaceHistoryMapperWithFactory<T>.
eg.:
final PlaceHistoryHandler placeHistoryHandler = new PlaceHistoryHandler(new CustomHistoryMapper());
You will be able then to map tokens as you wish.
I personally recommend you to use an unique PlaceTokenizer in you mapper custom implementation so that I dont have to have an inner PlaceTokenizer class in each of your Places.
Hope that helps. Feel free to ask any doubts.

Tell C# to use Castle to create objects

I think my question is a long shot.
Lets say I have an attribute:
public sealed class MyCustomAttribute: ActionFilterAttribute
Used on a class method
[MyCustomAttribute]
public virtual ActionResult Options(FormCollection collection)
Now, I need to add a contructor's parameter
public MyCustomAttribute(IMyDependentObject dependentObject)
{
(...)
}
(You propably notice that it's some Asp.NET MCV code)
I would like to use DI to create this attribute. Asp.NET MVC code automatically create it and I don't know how/where I could write code to use Castle istead.
Any ideas?
As far a I konw castle does not support injection of existing objects, which makes it impossible to inject attributes as their construction is not under your control. Other IoC containers such as Ninject support injection of existing objects. They inject properties of your attribut filter. See http://github.com/ninject/ninject.web.mvc for an extension that exactly does what you need.
What you can do if you want to stay on castle is to inject your own ControllerActionInvoker derived from ControllerActionInvoker (AsyncControllerActionInvoker in case of async controller) into all controllers. In your own invoker you override GetFilters. Additionally to the Filters returned by the base you add FilterInfos that are created by castle.
The decision which filters infos are created and added can be achieved with various strategies e.g.:
Add an own custom attribute that contains the information e.g. name of a binding
A configuration file/database
May you consider switching to MVC3 this makes all a bit easier. As you can register your own FilterProvider which makes all much easier. In this FilterProvider you have to decide which filter info you want to add. See again the two strategies above. See http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html for information about MVC3 and filters.

Programatic property injection with Microsoft Unity

I use contructor injection in my solution, but this one class has a property that i do not want to pass in the constructor where i have the invariant dependencies.
Let's say i got an ILogger and it has a FileName property i want to set, while still having it set the dependancies in the contructor.
How do i go about registering the type, and at the same time pass the defaunt connection string.
I hope there is an easy way to do it - preferably without decorating the property with an attribute, but if the setup is easier with the attribute i guess that's cool :)
So the question is, how do i inject a property value on an object that also uses contructor injection - with Unity.
UPDATE: I mentioned it in the title, but i forgot to elaborate in the body of the text - i want to set these dependencies up manually (in code) as opposed to in a config file.
Ok i guess it helped to ask the question, i found out - here it is.
container.Configure<InjectedMembers>().ConfigureInjectionFor<BasicLogger>(
new InjectionProperty("FileName", #"C:\test.log")
);
If you are injecting properties you have to use [Dependency] or else manually inject that dependency.
You usually want an IConfiguration interface to be injected. This would probably have a LogFile property that you can read.
The Configuration implimentation is usually just a simple wrapper to read items from the config file.

Windsor Container: How to specify a public property should not be filled by the container?

When Instantiating a class, Windsor by default treats all public properties of the class as optional dependencies and tries to satisfy them. In my case, this creates a rather complicated circular dependency which causes my application to hang.
How can I explicitly tell Castle Windsor that it should not be trying to satisfy a public property? I assume there must be an attribute to that extent. I can't find it however so please let me know the appropriate namespace/assembly.
If there is any way to do this without attributes (such as Xml Configuration or configuration via code) that would be preferable since the specific library where this is happening has to date not needed a dependency on castle.
You can use the Castle.Core.DoNotWireAttribute attribute to stop a property from being wired up by the IoC container (this is in the Castle.Core assembly, which means your library only needs to take a dependency on the lightweight Castle.Core assembly - if for example you want to use the code without an inversion of control container altogether, or in a different IoC container).
I don't believe there's any way to prevent wiring from occurring in the Xml configuration, but it would be reasonably easy to add support for this - if I had to do this I would probably:
Introduce some kind of attribute on the property declaration in the xml: <myprop wire="false" />
Inherit from PropertiesDependenciesModelInspector, overriding the InspectProperties method to apply some additional logic to identifying which properties should be added as dependencies to the components model (inspecting the model.Configuration for the wire="false" attribute/value pair).
Inherit from DefaultComponentModelBuilder and override the InitializeContributors to include your replacement PropertiesDependenciesModelInspector - or just remove the existing properties contributor and add your own at run time via the AddContributor/RemoveContributor methods.
Replace the ComponentModelBuilder service instance assigned to the kernel of your container.
Another approach which could work for you is to just manually remove the dependencies from the model before any instances of the service are requested ie.
kernel.GetHandler(typeof(MyComponent)).ComponentModel.Dependencies.RemoveAll(d => d.DependencyKey == "PropertyThatShouldNotBeWired");
YMMV with that approach though - especially if you have startable services or other facilities which may be eagerly instantiating your component after it's registered.
I created a facility to help with this:
Castle.Facilities.OptionalPropertyInjection
I do not know which version of Castle you guys were using at that time, but none of the solution mentioned were working. Plus, there is a lot of dead links.
With castle 3.1, here the solution I came up with (thanks to some castle source code digging):
container.Register(Component.For(type)
.LifestyleTransient()
.Properties( propertyInfo => propertyInfo.PropertyType != typeof(MyOtherType)));
The 'Properties' function adds a property filter used by castle when constructing the ComponentModel. In my case, all properties dependency will be satisfied except the property type 'MyOtherType'.
Maybe it will be helpful for someone. In Windsor 4.1 there is PropertiesIgnore method during registration.
Component.For<Role>().LifestyleTransient().PropertiesIgnore((model, propertyInfo) => true)
DoNotWireAttribute
Class: http://svn.castleproject.org:8080/svn/castle/trunk/Core/Castle.Core/Attributes/DoNotWireAttribute.cs
Test: http://svn.castleproject.org:8080/svn/castle/trunk/InversionOfControl/Castle.Windsor.Tests/IgnoreWireTestCase.cs
This can be achieved by the following code:
var container = new WindsorContainer();
// We don't want to inject properties, only ctors
var propInjector = container.Kernel.ComponentModelBuilder
.Contributors
.OfType<PropertiesDependenciesModelInspector>()
.Single();
container.Kernel.ComponentModelBuilder.RemoveContributor(propInjector);
Source Castle Windsor Documentation
Posted this on the google groups forum too here: http://groups.google.com/group/castle-project-devel/browse_thread/thread/43aa513817bd057a