Google Guice: Singleton with xml deserialization support? - singleton

in my project I need a class which contains the project configuration.
The configuration must be loaded from a XML file and must be a singleton.
In Guice there is a singleton scope. Now I have to "overwrite" the singleton with the deserialized configuration.
Is this somehow possible?

Important: pelase do note that Guice was originally created to get rid of all these huge and ugly XML files used by another DI library for managing dependencies. In general, when using Guice, you should be able to -almost- completely remove any XML from your project.
But if you must, perhaps because the XML file is generated by something outside your control then consider these:
Keep your whole configuration object and create a Provider for it, and bind it in Singleton scope. But you'll have to perform deserialization by yourself.
Or if your configuration is simply made of (name, value) pairs, then you can use java.util.Properties whcih can be loaded from an XML file, then use Guice Names.bindProperties() API in one of your Modules.
Then you can directly inject each single property by using #Inject #Named.

Related

How to inject dependency into a JsonConverter<>?

I would like to use a JsonConverter<> which has dependency, and that dependency can not be a singleton, instead should be resolve as scoped...
I have to configure my System.Text.JsonConverter in Startup, so I must provide the JsonSerializaionOptions along with my JsonConverter<> instance in Startup. I can live together the JsonConverter<> as singleton, I instantiate myself, but how can I inject its scoped dependencies?
The only horrible thing comes in my mind to have a IServiceProvider property, and some other logic later (middleware?) checks if that property is initialized and initializes it. So in the actual Read and Write methods of the JsonConverter<> can access to the scoped dependency via the IServiceProvider.
This sounds sooo errorprone and smells, once because of timing (what is the actual conversion occurs before the property injection), but my main concern is the concurrency, having this JsonConverter<> a singleton by design, so the very same IServiceProvider instance in the injected property will be used concurrently by all the web app threads...
What am I missing here?
Is having a scoped dependency for a JsonConverter<> smells?
Is there a way to not instantiate the JsonConverter<> in Startup? (yes I know I could instantiate JsonSerializerOptions and do manually the serialization with JsonConverter), but this way I can not use many built in json support of ASP.NET Core

Get the JAX-RS application a resource is attached on

I wonder if it's possible to get an instance of the JAX-RS Application a resource is attached on. Ideally a way that isn't dependent to a specific implementation. For example using dependency injection...
Thanks very much for your help,
Thierry
As stated in The Spec
5.2.1 Application
The instance of the application-supplied Application subclass can be injected into a class field or method parameter using the #Context annotation. Access to the Application subclass instance allows configuration information to be centralized in that class. Note that this cannot be injected into the Application subclass itself since this would create a circular dependency.
but from I've experienced, it will most likely not be the actual instance, but a proxy. Also if you're looking to alter anything on it, I'm not sure it's possible. It might be read-only.

How can i influence instance creation for annotated serializers

I wrote a jackson module to enable a specific type of serialization. Now i want to enable global configuration of one of the new serializers. so i have to set a property on a serializer instance during creation.
Is there a way i can do that from within a jackson module?
Module interface is stateless, one-of-thing, so it does not have default wiring to affect things it adds.
But what you can do is to use a work-around; possibilities include:
use of ThreadLocal; set before serialization, read from serializer
use new (Jackson 2.3) feature of "attributes"; can set those for writing (ObjectWriter.setAttribute()) and reading (ObjectReader.setAttribute()), accessible by serializer/deserializer through context object (SerializerProvider / DeserializationContext)
So hopefully one of these works for your use case.

How to wire up WCF Service Application, Unity and AutoMapper

I have been playing around the last couple of days with different solutions for mapping DTO's to entities for a VS2013, EF6, WCF Service App project.
It is a fairly large project that is currently undergoing a major refactoring to bring the legacy code under test (as well as port the ORM from OpenAccess to EF6).
To be honest I had never used AutoMapper before but what I saw I really liked so I set out to test it out in a demo app and to be honest I am a bit ashamed that I have been unable to achieve a working solution after hours of tinkering and Googling. Here is a breakdown of the project:
WCF Service Application template based project (.svc file w/code behind).
Using Unity 3.x for my IoC container and thus creating my own ServiceHostFactory inheriting from UnityServiceHostFactory.
Using current AutoMapper nuget package.
DTO's and DAL are in two separate libraries as expected, both of which are referenced by the service app project.
My goal is simple (I think): Wire up and create all of my maps in my composition root and inject the necessary objects (using my DI container) into the class that has domain knowledge of the DTO's and a reference to my DAL library. Anyone that needs a transformation would therefore only need to reference the transformation library.
The problem: Well, there are a couple of them...
1) I cannot find a working example of AutoMapper in Unity anywhere. The code snippet that is referenced many times across the web for registering AutoMapper in Unity (see below) references a Configuration class that doesn't seem to exist anymore and I cannot find any documentation on its deprecation:
container.RegisterType<AutoMapper.Configuration, AutoMapper.Configuration>(new PerThreadLifetimeManager(), new InjectionConstructor(typeof(ITypeMapFactory),
AutoMapper.Mappers.MapperRegistry.AllMappers())).RegisterType<ITypeMapFactory,
TypeMapFactoy>().RegisterType<IConfiguration, AutoMapper.Configuration>().RegisterType<IConfigurationProvider,
AutoMapper.Configuration>().RegisterType<IMappingEngine, MappingEngine>();
2) Where to create the maps themselves... I would assuming that I could perform this operation right in my ServiceHostFactory but is that the correct place? There is a Bootstrapper project out there but I have not gone down that road (yet) and would like to avoid it if possible.
3) Other than the obviously necessary reference to AutoMapper in the DTO lib, what would I be injecting into the instantition, the configuration object (assuming IConfiguration or IConfigurationProvider) and which class I am injecting into the constructor of the WCF service to gain access to the necessary object.
I know #3 is a little vague but since I cannot get AutoMapper bound in my Unity container, I cannot test/trial/error to figure out the other issues.
Any pointers would be greatly appreciated.
UPDATE
So I now have a working solution that is testing correctly but would still like to get confirmation that I am following any established best practices.
First off, the Unity container registration for AutoMapper (as of 11/13/2013) v3.x looks like this:
container
.RegisterType<ConfigurationStore, ConfigurationStore>
(
new ContainerControlledLifetimeManager()
, new InjectionConstructor(typeof(ITypeMapFactory)
, MapperRegistry.AllMappers())
)
.RegisterType<IConfigurationProvider, ConfigurationStore>()
.RegisterType<IConfiguration, ConfigurationStore>()
.RegisterType<IMappingEngine, MappingEngine>()
.RegisterType<ITypeMapFactory, TypeMapFactory>();
Right after all of my container registrations, I created and am calling a RegisterMaps() method inside of ConfigureContainer(). I created a test mapping that does both an auto mapping for like named properties as well as a custom mapping. I did this in my demo app for two reasons primarily:
I don't yet know AutoMapper in a WCF app hosted in IIS and injected with Unity well enough to fully understand its behavior. I do not seem to have to inject any kind of configuration object into my library that does the transformations and I am still reading through the source to understand its implementation.
As I understand it, there is a caching mechanism at play here and that if a mapping is not found in cache that it will create it on the fly. While this is great in theory, the only way I could then test my mappings that were occurring in my composition root was to do some sort of custom mapping and then call Mapper.Map in the library that performs mapping and returns the DTO.
All of that blathering aside, here is what I was able to accomplish.
WCF Service App (composition root) injects all of the necessary objects including my DtoConversionMapper instance.
The project is made up of the WCF Service App (comp root), DtoLib, DalLib, ContractsLib (interfaces).
In my ServiceFactoryHost I am able to create mappings, including custom mappings (i.e. map unlike named properties between my DTO and EF 6 entity).
The DtoConversionMapper class lives in the DtoLib library and looks like this: IExampleDto GetExampleDto(ExampleEntity entity);
Any library with a reference to the DtoLib can convert back and forth, including the Service App where the vast majority of these calls will take place.
Any guiding advice would be greatly appreciated but I do have a working demo now that I can test things out with while I work through this large refactoring.
Final Update
I changed the demo project just a little by adding another library (MappingLib) and moved all of my DTO conversions and mappings to it in a static method. While I still call the static method in my composition root after the Unity container is initialized, this gives me the added flexibility of being able to call that same map creation method in my NUnit unit test libraries, effectively eliminating any duplication of code surrounding auto mapper and makes it very testable.

Save and Load instances of objects created earlier via the Eclipse registry

I am currently experiencing a problem in my RCP application and wanted to ask, if someone stumbled over the same problem and can give me some valuable hints:
My RCP application allows plugins to provide implementations of a specific abstract class of my model (singleton) to extend my model during runtime via the update manager. I instantiate these classes via
extensionPointImplementation.createExecutableExtension(..)
after parsing the Eclipse registry. I can serialize the created instances using the default Java serialization API.
Now to the problem: The plugin trying to deserialize the objects cannot find the class implementations of the model extensions due to the fact, that there is no plugin dependency between the plugins. Nevertheless, it is not possible for me to create such a dependency which would make the idea of extending the model during runtime obsolete.
Is it possible to solve this problem by using the default Java serialization API or do I have to implement my own serialization (which parses the Eclipse registry and creates the instances via the line shown above if all necessary plugins are available, otherwise throw an exception) which might be based on the default Java serialization API (if possible I do not want to create the serialization completely by myself)?
Thanks.
You need to define a so called buddy policy.
In the bundle trying to instantiate the class add
Eclipse-BuddyPolicy: registered
to the manifest.mf.
In the bundle providing the class add
Eclipse-RegisterBuddy: <symbolic name of the bundle instantiating the class>
to the manifest.mf.