I have implement simple EJB 3.0 deployed it on weblogic 12c. The EJB contains a reference to a different EJB as a member declared as a reference of implemented local interface with annotation #EJB. When I invoke a method of the encapsulated EJB I get a null pointer exception. The same does not happen when I inject session context or data source using #SessionContext or #Resource respectivley. What I want to understand is do I have to define a reference in
in weblogic.xml for linking two EJBs. Is this same for all production grade application servers like jboss, websphere or Tomcat EE.
Here is more details about code & deployment:
#Remote
public interface MyEjbRemote1 {
abstract public void func1();
}
#Stateless
public class MyEJB1 implements MyEjbRemote1 {
public void func1() {}
}
#Remote
public interface MyEjbRemote {
abstract public void func();
}
#Stateless
public class MyEjb implements MyEjbRemote, MyEjbLocal {
#EJB
MyEjbRemote1 ejb1;
#Resource
SessionContext sessionContext;
public void func() {
ejb1.func1();
}
public void func1() {
System.out.println("Local interface call for EJB");
}
}
The call to func1 method using remote interface is throwing a null pointer exception.
I have not put any details in ejb-jar.xml, weblogic-ejb-jar.xml or weblogic.xml. My question is what addition details is required.
Related
In the process of setup a bridge between guice and jersey, I ran into one problem.
When trying to create a jersey filter, I was unable to inject guice dependencies into it.
I found a duplicate, however there is no solution to the problem there.
Everything is exactly the same.
The only difference is that I don't get a startup error. The filter works, but my dependencies are null.
Interestingly, Filter and HttpFilter work fine. But it doesn't really work for me.
There's another thing that's interesting. In the resource, which I understand is an HK2 dependency, I can inject guice bean.
#ApplicationPath("/test")
private static class TestApplicationConfig extends ResourceConfig
{
public TestApplicationConfig()
{
register(JacksonFeature.class);
register(AuthFilter.class);
register(new ContainerLifecycleListener()
{
public void onStartup(Container container)
{
ServletContainer servletContainer = (ServletContainer) container;
ServiceLocator serviceLocator = container.getApplicationHandler().getServiceLocator();
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
Injector injector = (Injector) servletContainer
.getServletContext()
.getAttribute(Injector.class.getName());
guiceBridge.bridgeGuiceInjector(injector);
}
public void onReload(Container container)
{
}
public void onShutdown(Container container)
{
}
});
}
}
In ServletModule child.
serve(path).with(ServletContainer.class, ImmutableMap.of(
"javax.ws.rs.Application", TestApplicationConfig.class.getName(),
"jersey.config.server.provider.packages", sb.toString()));
I trying with register(AuthFilter.class) and #Provider
#Singleton
#Provider
public class AuthFilter implements ContainerRequestFilter
{
#Inject
private SomeInjectedService someInjectedService; **// null here**
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext requestContext) throws IOException
{
// some code
}
}
SomeInjectedService I register by guice
bind(SomeInjectedService.class).asEagerSingleton();
Where can I start diagnosing and what can I do?
UPD:
I noticed different behavior when using different annotations.
If I use javax.inject.Inject, I get the following error message.
org.glassfish.hk2.api.MultiException: A MultiException has 3 exceptions. They are:
1. org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=SomeInjectedService,parent=AuthFilter,qualifiers={},position=-1,optional=false,self=false,unqualified=null,1496814489)
2. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of some.package.AuthFilter errors were found
3. java.lang.IllegalStateException: Unable to perform operation: resolve on some.package.AuthFilter
If com.google.inject.Inject, just null. As I understand this method is not correct.
Considering that javax Inject is trying to inject the service but can't find it. Can we conclude that the bridge is not working correctly? But if it's not working correctly, why can I inject this service into my resource?
#Path("/test")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class SomeResource
{
private final SomeInjectedService someInjectedResource;
#Inject // here I use javax annotation and this code working correctry
public SomeResource(SomeInjectedService someInjectedResource)
{
this.someInjectedResource = someInjectedResource;
}
#GET
#Path("/{user}")
public Response returnSomeResponse(#PathParam("user") String user) throws Exception
{
// some code
}
}
I have an Azure Functions project that leverages Dependency Injection (Startup.cs injects services based on the different interfaces). Those services that implement the interfaces are using constructor dependency injection as well.
In one of those implementations, I want to call a method on a Durable Entity, but I prefer not to make the DurableEntityClient part of the method signature (as other implementations might not need the EntityClient at all). So therefore, I was hoping to see that IDurableEntityClient injected in the constructor of my class.
But it turns out the value is null. Wondering if this is something that is supported and feasible? (to have a DI-friendly way of injecting classes that want to get the EntityClient for the Functions runtime they are running in)
Some code snippets:
Startup.cs
builder.Services.AddSingleton<IReceiver, TableReceiver>();
Actual Function
public class ItemWatchHttpTrigger
{
private IReceiver _receiver;
public ItemWatchHttpTrigger(IReceiver receiver)
{
_receiver = receiver;
}
[FunctionName("item-watcher")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "item/{itemId}")]
HttpRequest request, string itemId, [DurableClient] IDurableEntityClient client, ILogger logger)
{
// Actual implementation
}
}
Referenced class
public class TableReceiver : IReceiver
{
private IDurableEntityClient _entityClient;
public TableReceiver(IDurableEntityClient client)
{
_entityClient = client; // client is null :(
}
}
Based on the answer of my github issue, it seems it is possible to inject this in Startup, since the 2.4.0 version of the Microsoft.Azure.WebJobs.Extensions.DurableTask package:
Some code snippets:
Startup.cs
builder.Services.AddSingleton<IReceiver, TableReceiver>();
builder.Services.AddDurableClientFactory();
Referenced class
public class TableReceiver : IReceiver
{
private IDurableEntityClient _entityClient;
public TableReceiver(IDurableClientFactory entityClientFactory, IConfiguration configuration)
{
_entityClient = entityClientFactory.CreateClient(new DurableClientOptions
{
TaskHub = configuration["TaskHubName"]
});
}
}
Github issue
tldr: Is there any way I can choose which constructor to use when I register a type?
I have followed the instructions to create a platform specific inversion of control as outlined in Inversion of control.
In your core project, you can declare an interface and you can use
that interface in your classes there ...
In each UI project, you can then declare the platform-specific
implementation ...
You can then register these implementations in each of the
platform-specific Setup files - e.g. you could override
MvxSetup.InitializeFirstChance
So in my core project I have defined the following interface
public interface IJob
{
void AddAction(Action action);
}
In my Android project I have implemented the interface as follows
public class CustomJob: Job, IJob
{
private Action _action;
public CustomJob(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public CustomJob() : base(new Params
(Jobs.Priority.MID
).RequireNetwork().Persist())
{
//_action = action;
}
public override void OnAdded()
{
}
protected override void OnCancel(int p0, Throwable p1)
{
}
public override void OnRun()
{
_action.Invoke();
}
protected override RetryConstraint ShouldReRunOnThrowable(Throwable p0, int p1, int p2)
{
return RetryConstraint.Cancel;
}
public void AddAction(Action action)
{
_action = action;
}
}
And I overrode the implementation of InitializeFirstChance in Setup.cs
protected override void InitializeFirstChance()
{
Mvx.IoCProvider.RegisterType<IJob, CustomJob>();
base.InitializeFirstChance();
}
However, I get the following stacktrace at runtime
{MvvmCross.Exceptions.MvxIoCResolveException: Failed to resolve
parameter for parameter javaReference of type IntPtr when creating
CustomJob. You may pass it as an argument at
MvvmCross.IoC.MvxIoCContainer.GetIoCParameterValues (System.Type type,
System.Reflection.ConstructorInfo firstConstructor,
System.Collections.Generic.IDictionary2[TKey,TValue] arguments)
[0x0005a] in
C:\projects\mvvmcross\MvvmCross\IoC\MvxIoCContainer.cs:648 at
MvvmCross.IoC.MvxIoCContainer.IoCConstruct (System.Type type,
System.Collections.Generic.IDictionary2[TKey,TValue] arguments)
[0x00031] in
C:\projects\mvvmcross\MvvmCross\IoC\MvxIoCContainer.cs:413
Is there any way I can choose which constructor to use when I register a type? Thank you.
AFAIK you can't choose which constructor the Mvx's IoC engine will choose.
So one way is to make another class that implements your IJob that has a reference to Job internally and in the implementation of the class you pass the action to the Job implementation.
public class JobHandler : IJob
{
private Job _customJob;
public JobHandler()
{
this._customJob = new CustomJob();
}
public void AddAction(Action action)
{
this._customJob.AddAction(action);
}
}
If you want you can do an IJobHandler that inherits IJob so that you can use that interface for the JobHandler implementations and the IJob for you actual Job
Another way is to add stub parameters to the parameterless constructor so that it takes more parameters than the other and gets elected by the IoC engine (I'm not entirely sure that it would work, but I think so). But it is a bit messy.
Another way is you to tell the IoC engine how you want to construct your IJob:
Mvx.IoCProvider.RegisterType<IJob>(() => new CustomJob());
HIH
Most of the examples I've found for Automapper use the static Mapper object for managing type mappings. For my project, I need to inject an IMapperEngine as part of object construction using StructureMap so that we can mock the mapper in unit tests so we can't use the static mapper. I also need to support configuring AutoMapper Profiles.
My question is how can I configure the StructureMap registry so that it can supply an instance of IMappingEngine when an instance of MyService is constructed.
Here is the Service constructor signature:
public MyService(IMappingEngine mapper, IMyRepository myRepository, ILogger logger)
And here is the StructureMap Registry
public class MyRegistry : StructureMap.Configuration.DSL.Registry
{
public MyRegistry()
{
For<IMyRepository>().Use<MyRepository>();
For<ILogger>().Use<Logger>();
//what to do for IMappingEngine?
}
}
And the profile I want to load
public class MyAutoMapperProfile : AutoMapper.Profile
{
protected override void Configure()
{
this.CreateMap<MyModel, MyDTO>();
}
}
The Mapper class has a static property Mapper.Engine. Use this to register the engine with the container:
For<IMappingEngine>().Use(() => Mapper.Engine);
If you need to load your profiles before injecting the engine I would insert that configuration code alongside the above snippet.
Update
Your custom registry would look like this
class MyRegistry : Registry
{
public MyRegistry()
{
For<IMyRepository>().Use<MyRepository>();
For<ILogger>().Use<Logger>();
Mapper.AddProfile(new AutoMapperProfile());
For<IMappingEngine>().Use(() => Mapper.Engine);
}
}
This code runs once in your bootstrapper and any dependency of type IMappingEngine will afterwards be served with the value of the static property Mapper.Engine which is configured using your custom AutoMapperProfile.
The static API will be removed in version 5.0. Use a
MapperConfiguration instance and store statically as needed. Use
CreateMapper to create a mapper instance.
in new version (4.2.0 >=) we should hold and pass IMapper through DI.
a simple Configure Service should be like this (ASP.NET Core)
services.AddSingleton<IMapper>(_ => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo,Bar>();
})
.CreateMapper());
and our service layer (with the help of constructor injection) :
public class CrudService<TDocument> : ICrudService<TDocument>
{
private readonly IMapper _internalMapper;
private readonly IRepository<TDocument> _repository;
public CrudService(IRepository<TDocument> repository, IMapper mapper)
{
_internalMapper = mapper;
_repository = repository;
}
public virtual ServiceResult<string> Create<TModel>(TModel foo)
{
var bar = _internalMapper.Map<TDocument>(foo);
try
{
_repository.Create(bar);
}
catch (Exception ex)
{
return ServiceResult<string>.Exception(ex);
}
return ServiceResult<string>.Okay(entity.Id);
}
}
consider TDocument as Bar, and TModel as Foo
update :
AutoMapper 4.2.1 released – Static is back
After a bit of feedback and soul searching and honestly tired of
dealing with questions, some of the static API is restored in this
release. You can now (and in the future) use Mapper.Initialize and
Mapper.Map
I wrote a blog post that shows my AutoMapper with StructureMap setup. I have created specific registries for AutoMapper 3.1.0 (also works for 3.1.1) and 3.0.0 and 2.2.1.
http://www.martijnburgers.net/post/2013/12/20/My-AutoMapper-setup-for-StructureMap.aspx
Here's what I ended up with as I couldn't figure out how to set the configuration on Mapper.Engine and have it passed into For().Use.
public MyRegistry()
{
For<IMyRepository>().Use<MyRepository>();
For<ILogger>().Use<Logger>();
//type mapping
For<ConfigurationStore>()
.Singleton()
.Use(ctx =>
{
ITypeMapFactory factory = ctx.GetInstance<ITypeMapFactory>();
ConfigurationStore store
= new ConfigurationStore(factory, MapperRegistry.AllMappers());
IConfiguration cfg = store;
cfg.AddProfile<MyAutoMapperProfile>();
store.AssertConfigurationIsValid();
return store;
});
For<IConfigurationProvider>().Use(ctx => ctx.GetInstance<ConfigurationStore>());
For<IConfiguration>().Use(ctx => ctx.GetInstance<ConfigurationStore>());
For<IMappingEngine>().Singleton().Use<MappingEngine>();
For<ITypeMapFactory>().Use<TypeMapFactory>();
}
I'm trying to use StructureMap with nServiceBus.
The Project:
Uses a GenericHost Endpoint to send command messages
Configures nServiceBus using the StructMapBuilder.
Uses a simple StructureMap registry config
Uses a start up class TestServer supporting IWantToRunAtStartup
The TestServer class has ctor dependency on a TestManager class
The TestManager class has ctor dependency on IBus
ObjectFactory.WhatDoIHave() shows StructureMap knows how to construct the classes.
When run I get buildup errors. nServiceBus seems to be overwriting the config?
Note that when I add a IBus ctor depenendency to my event handlers without any other config all appears fine.
Error:
Exception when starting endpoint, error has been logged. Reason: Error creating object with name 'nSeviceBusStructureMapTest.TestServer' : Unsatisfied dependency expressed through constructor argument with index 0 of type [nSeviceBusStructureMapTest.ITestManager] : No unique object of type [nSeviceBusStructureMapTest.ITestManager] is defined : Unsatisfied dependency of type [nSeviceBusStructureMapTest.ITestManager]: expected at least 1 matching object to wire the [miningServiceManage] parameter on the constructor of object [nSeviceBusStructureMapTest.TestServer]
Source:
using System;
using System.Diagnostics;
using NServiceBus;
using StructureMap;
using StructureMap.Configuration.DSL;
namespace nSeviceBusStructureMapTest
{
public class TestSmRegistry : Registry
{
public TestSmRegistry()
{
For<ITestManager>().Use<TestManager>();
For<TestServer>().Use<TestServer>();
}
}
public class TestEndPoint : AsA_Server, IConfigureThisEndpoint
{
public void Init()
{
Configure.With().StructureMapBuilder(ObjectFactory.Container);
ObjectFactory.Configure(c => c.AddRegistry<TestSmRegistry>());
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
}
public class TestServer : IWantToRunAtStartup
{
public TestServer(ITestManager miningServiceManage)
{
_miningServiceManage = miningServiceManage;
}
private readonly ITestManager _miningServiceManage;
public void Run()
{
_miningServiceManage.Run();
}
public void Stop() { }
}
public interface ITestManager
{
void Run();
}
public class TestManager : ITestManager
{
public TestManager(IBus bus)
{
_bus = bus;
}
private readonly IBus _bus;
public void Run()
{
if (_bus == null) Debug.WriteLine("Error no bus");
// Send messages on bus;
}
}
}
<MsmqTransportConfig InputQueue="test" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />
<UnicastBusConfig>
<MessageEndpointMappings>
</MessageEndpointMappings>
</UnicastBusConfig>
Any ideas?
You have to specify IWantCustomInitialization on the endpoint config class. Otherwise NServiceBus won't call the Init() method. You also need to specify what serializer to use so add:
Configure.With()
.StructureMapBuilder()
.XmlSerializer();
Hope this helps!