Autofac An error occurred during the activation of a particular registration - autofac

I have inherited a .NET project which keeps throwing Autofac errors but I'm not sure what this error message is telling me. Any help would be appreciated?
An error occurred during the activation of a particular registration. See the inner exception for details.
Registration:
Activator = ImplementationResourceRepository (ReflectionActivator),
Services = [Interfaces.IImplementationResourceRepository],
Lifetime = Autofac.Core.Lifetime.CurrentScopeLifetime,
Sharing = None,
Ownership = OwnedByLifetimeScope ---> None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'CCES.Repositories.ImplementationResourceRepository' can be invoked with the available services and parameters:
Cannot resolve parameter 'Interfaces.IRepository repository' of constructor 'Void .ctor(Interfaces.IRepository)'. (See inner exception for details.)

Type ImplementationResourceRepository has a constructor that takes an instance that implements Interfaces.IRepository in it's constructor but no types were registered as Interfaces.IRepository. You need to register a type that implementats Interfaces.IRepository as that interface with Autofac.
Something similar to this:
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<Implementations.Repository>()
.As<Interfaces.IRepository>()
.InstancePerDependency();
}

Related

Does Crud Repository has saveAll method that works?

I am trying to use CRUDRepository for my development project. I have seen in many posts that CRUD Repository do support saveAll method which allows to save a list of object in the database. But when I am using it, It is giving me an error that saveAll property is not found
Here is the detailed error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BinaryPartCRUDRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query method public abstract java.util.List xxx.xxx.xx.xxxx.repository.BinaryPartCRUDRepository.saveAll(java.util.List)! No property saveAll found for type BinaryPart!
Here is my code.
public interface BinaryPartCRUDRepository extends CrudRepository<BinaryPart, Long> {
BinaryPart save(BinaryPart binaryPart);
List<BinaryPart> saveAll(List<BinaryPart> binaryParts);
}
The save Function is working. But saveAll is not.
I have also tried to use the Persistence manager to do the batch save. But having null object while doing JUnit Testing. So I am preferring to stay with CRUD Repository. Appreciate any kind of suggestion.
saveAll already there in CrudRepository, so no need to specify your own method for save all in repository interface.
remove this part:
List<BinaryPart> saveAll(List<BinaryPart> binaryParts);
and in your service class , directly call `saveAll method. Remember this method using iterable as param and return value.
The saveAll method has the following signature:
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
You define an additional method with the same name, but a different signature. Spring Data does not know how to create an implementation for that and throws the exception.
Just change your interface to:
public interface BinaryPartCRUDRepository extends CrudRepository<BinaryPart, Long> {}
And you are good to go.

How do I register an interface to the EntityFramework.UserStore<TUser> constructor?

I have been following this post to learn about DI with AutoFac. My DB context is registered in Startup.cs like this:
builder.RegisterType<MyDb>().As<IMyDbCtx>().InstancePerRequest();
I also followed the instructions to create the ApplicationUserStore class, and registered this type like so:
builder.RegisterType<ApplicationUserStore>().As<IUserStore<ApplicationUser>>().InstancePerRequest();
This was all fine until I realized that ApplicationUserStore is expecting a concrete DbContext in it's constructor to pass to its base constructor:
public ApplicationUserStore(MyDb context)
: base(context)
{
}
When I run the application and try loading the registration page, this is the error I see:
None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'TestApp.Service.IdentityConfig.ApplicationUserStore' can be invoked with the available services and parameters:
Cannot resolve parameter 'TestApp.Data.MyDb context' of constructor 'Void .ctor(MyApp.Data.MyDb)'.
This is breaking, I assume, because I already set up MyDb as a IMyDbCtx, so it won't accept the concrete type. This is good because I don't want to be inconsistent by injecting abstractions in some spots and implementations in others.
Does anyone have any ideas on how I can pass in an IMyDbCtx to the UserStore ctor, particularly with AutoFac?
This is not an ideal solution, but I decided to cast the interface to the concrete type when the parameter is passed to the base constructor:
public ApplicationUserStore(IMyDbCtx context)
: base((MyDb)context)
{
}
You can register your type MyDb under as many aliases as you wish:
builder.RegisterType<MyDb>()
.As<MyDb>()
.As<IMyDbCtx>()
.InstancePerRequest();
In this case Autofac can resolve Application User Store. But it kills the whole idea of dependency injection, because you feed the concrete type.

Autofac doesnot cannot resolve types when in IIS sub application

Does any one know why autofac fails to initialize the mvc controllers when there is an applicaton in the root and also another in sub application in IIS? How to fix this?
When the apps are hosted in different Websites in IIS they work without a problem.
so in the image, the root app(mvc web) deployed in the root works but not the webservice (mvc api).
error is
An error has occurred.An error occurred when trying to create a controller of type 'UserController'. Make sure that the controller has a parameterless public constructor.System.InvalidOperationException at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()An error has occurred.An exception was thrown while invoking the constructor 'Void .ctor()' on type 'BurpDaddyEntities'. ---> The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. (See inner exception for details.)Autofac.Core.DependencyResolutionException at Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate()
at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable1 parameters)
at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters)
While the top-level exception appears to be from Autofac, if you look down at the inner exception issue that caused the whole thing, you'll see the true exception is The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception. Which means the static constructor for that class went awry.
Fortunately, there's actually a question (with an answer!) directly about exactly what you're facing here with nested websites using Entity Framework:
The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception on a Sub Website

Sharprepository Autofac InstancePerApiRequest in Webapi environment not working

Does anyone have a working example of sharprepository intergration with autofac using InstancePerApiRequest for DbContext?
I am registering my dbcontext thusly:
builder.RegisterType<AuditTestEntities>().As<DbContext>().InstancePerApiRequest();
If I remove the InstancePerApiRequest, sharprepository is able to get a dbcontext. But with the InstancePerApiRequest, I get the error message pasted below. Basically the crux of the error is, I suspect, the way sharprepository makes the call:
No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
The full error stack:
iisexpress.exe Error: 0 : Operation=DefaultHttpControllerActivator.Create, Exception=System.InvalidOperationException: An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor. ---> Autofac.Core.DependencyResolutionException: An exception was thrown while invoking the constructor 'Void .ctor()' on type 'AccountRepository'. ---> Could not resolve type 'System.Data.Entity.DbContext' using the 'AutofacDependencyResolver'. Make sure you have configured your Ioc container for this type. View the InnerException for more details. (See inner exception for details.) ---> SharpRepository.Repository.Ioc.RepositoryDependencyResolverException: Could not resolve type 'System.Data.Entity.DbContext' using the 'AutofacDependencyResolver'. Make sure you have configured your Ioc container for this type. View the InnerException for more details. ---> Autofac.Core.DependencyResolutionException: No scope with a Tag matching 'AutofacWebRequest' is visible from the scope in which the instance was requested. This generally indicates that a component registered as per-HTTP request is being requested by a SingleInstance() component (or a similar scenario.) Under the web integration always request dependencies from the DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime, never from the container itself.
Okay found the issue. There is a problem with using the SharpRepository AutofacDependencyResolver when using the MVC or Web API integration and trying to use the scope InstancePerApiRequest or InstancePerHttpRequest. Autofac expects those items to be resolved from the System.Web.DependencyResolver.Current instead of from the Autofac IContainer directly as the AutofacDependencyResolver is currently doing.
Here is how you can fix the issue right now until we make an overload for AutofacDependencyResolver that fixes the issue.
You will need to create your own dependency resolver within your project like this one:
public class CustomAutofacDependencyResolver : BaseRepositoryDependencyResolver
{
private readonly IDependencyResolver _resolver;
public CustomAutofacDependencyResolver(IDependencyResolver resolver)
{
_resolver = resolver;
}
protected override T ResolveInstance<T>()
{
return _resolver.GetService<T>();
}
protected override object ResolveInstance(Type type)
{
return _resolver.GetService(type);
}
}
And then register it with SharpRepository so it will use it to resolve the DbContext and then it will work as expected.
RepositoryDependencyResolver.SetDependencyResolver(new CustomAutofacDependencyResolver(DependencyResolver.Current));
** Update**
I was testing with MVC and able to replicate the error and fix it but that doesn't work with Web API. I am used to using StructureMap where it works fine using the GlobalConfiguration.Configuration.DependencyResolver.
It seems the issue is that Autofac needs a IDependencyScope that you can access from the HttpRequestMessage but I'm not seeing a way to get to that outside of the ApiController. This describes the issue and the reason: https://groups.google.com/forum/#!msg/autofac/b3HCmNE_S2M/oMmwFE5uD80J
Unfortunately right now I'm at a bit of a loss on the best way to handle this. But I'll keep thinking about it.
So, I was able to get mine working by changing the lifetime scope to InstancePerLifetimeScope. I don't know whether this has any unforeseen consequences or not. Everything appears to be working fine for me so far.

GWT RequestContext ENum in the request

If we use enum as one of the attribute in the Request invocation , it throws an UnsupportedOpeationException and does not even invoke the service method on the server.
#Service(value = DesignService.class, locator = DesignServiceLocator.class)
public interface DesignRequest extends RequestContext {
Request<List<DesignProxy>> findDesign(SortEnum sortorder);
}
when we invoke the designRequest.findDesign(sortorderEnum).fire() the UnsupportOperationException is thrown on the javascript console on chrome dev tools/Firebug console.
Looks like it is related to Issue 6504, which will throw an UnsupportedOperationException if it fails to find the type you are using - consider trying to change to class methods in your enum, or wait until 2.4 is released.
If you are not using anonymous enum instances, can you post more info about this error, such as where the exception is thrown from?