w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Autofac Register Different Implementation To Different Controllers
Have you assigned the names "TestService1" and "TestService2"? e.g. builder.RegisterType<TestService1>().As<ITestService1>().Named("TestService1"); builder.RegisterType<TestService2>().As<ITestService2>().Named("TestService2");

Categories : Asp Net Mvc

Autofac - Register multiple decorators
You just need to register your "TransactionCommandHandlerDecoratored" ICommandHandler as a Keyed service and use that new key when registering your second DeadlockRetryCommandHandlerDecorator: builder.RegisterGenericDecorator( typeof(TransactionCommandHandlerDecorator<>), typeof(ICommandHandler<>), fromKey: "commandHandler") .Keyed("decorated", typeof(ICommandHandler<>)); builder.RegisterGenericDecorator( typeof(DeadlockRetryCommandHandlerDecorator<>), typeof(ICommandHandler<>), fromKey: "decorated"); And you will get the following output: DeadlockRetryCommandHandlerDecorator - before TransactionCommandHandlerDecorator - before MoveCustomerCommandHandler TransactionCommandHandlerDecorator - after Dea

Categories : C#

How to register two WCF service contracts with autofac
Update (the bold text) based on @nemesv's answer: Further investigation revealed that with autofac one cannot register multiple endpoints on a single ServiceHost if one registers the WCF service contracts. (See @nemesv's answer for the correct way to do it.) Here is why: Either form of this extension method... host.AddDependencyInjectionBehavior<IService1>(_container); host.AddDependencyInjectionBehavior(t, container); ...resolves down to adding a ServiceBehavior (according to Alex Meyer-Gleaves initial announcement of WCF integration in autofac)... host.Description.Behaviors.Add(behavior); Now this Behaviors property is an instance of KeyedByTypeCollection<TItem>, which can hold only only one object of a given type. Since the behavior being added will always be an ins

Categories : C#

Register Autofac decorator for only one generic command handler
After smacking my head against keyboard enough times, I've got some kind of solution to my problem: static class AutofacRegistration { public static IContainer RegisterHandlers() { var builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(AutofacRegistration))) .AsClosedTypesOf(typeof(ICommandHandler<>)) .InstancePerLifetimeScope(); builder.RegisterType<TestCommandHandler>() .Named<ICommandHandler<TestCommand>>("TestHandler") .InstancePerLifetimeScope(); // this works! builder.Register(c => new TestCommandHandlerDecorator(c.ResolveNamed<ICommandHandler<TestCommand>>("TestHandler"))) .As<IComm

Categories : C#

Castle windsor: Register generics with more than one items
It fails to compile because you specific generic types with one single parameter, but you defined types with two parameters. So you should use IGenericRepository<,> and GenericRepository<,> instead of IGenericRepository<> and GenericRepository<>.

Categories : C#

Simple injector to register open generics with multiple constructors
since it doesn't support registration for an specific constructor out of the box Simple Injector doesn't support this for a good reason. You should prefer letting your components have a single public constructor. Having multiple constructors is considered to be an anti-pattern. If for some reason you can't follow this advice, here are some alternatives. A simple solution would be to create a new type inside your Composition Root that inherits from the open generic type and defines just one single constructor. You can register that type instead: // new sub type private sealed class SingleCtorOpenType<T> : OpenType<T> { public SingleCtorOpenType(IDep1 dep1, IDep2 dep2) : base(dep1, dep2) { } } // registration container.RegisterOpenGeneric( typeof(IOpen

Categories : C#

Autofac register a class which is created by another class
I think I've got it builder.Register<OpeningHours>(c => { var cc = c.Resolve<StoreInformationService>(); return cc.OpeningHours; });

Categories : Asp Net Mvc

Generics - Using parent class to specify type in generics
The only way of doing that is with an out generic restriction (which will make it hard to save objects, but fine to retrieve them), on an interface (not a class). If you have: interface IGenericRepository<out T> {...} then an IGenericRepository<ProductStyle> can be assigned to a variable of type IGenericRepository<BaseEntity>, since all ProductStyle are also BaseEntity, and we have restricted ourselves to covariant / out usage: IGenericRepository<BaseEntity> tmp = GetRepo<ProductStyle>(context); // note that the right-hand-side returns IGenericRepository<ProductStyle> ... private IGenericRepository<T> GetRepo(...) {...} Note, however, that this covariant / out usage makes it impossible to do things like: interface IGenericRepository<out T

Categories : C#

Java, Subclass return generics of generics
Here's how to fix the problem: public class Test { public static void main(String[] args) { Human<Blond, Bob> h = new Human<Blond, Bob>(); Blond blond = h.getPerson().getHair(); blond = h.getDirectHair(); } } class Human<H extends Hair, T extends Person<H>>{ private T person = null; public T getPerson() { return person; } public H getDirectHair(){ return person.getHair(); } }

Categories : Java

Microarchitectural zeroing of a register via the register renamer: performance versus a mov?
Executive summary: You can run up to four xor ax, ax instructions per cycle as compared to the slower mov immediate, reg instructions. Details and references: Wikipedia has a nice overview of register renaming in general: http://en.wikipedia.org/wiki/Register_renaming Torbj¨orn Granlund's timings for instruction latencies and throughput for AMD and Intel x86 processors are at: http://gmplib.org/~tege/x86-timing.pdf Agner Fog nicely covers the specifics in his Micro-architecture study: 8.8 Register allocation and renaming Register renaming is controlled by the register alias table (RAT) and the reorder buffer (ROB) ... The µops from the decoders and the stack engine go to the RAT via a queue and then to the ROB-read and the reservation station. The RAT can handle 4

Categories : Assembly

GCM (Google cloud messaging) - can I register multiple devices with same register id?
No. Moreover, you should not need to. You can use user notifications to be able to send a single message from the server to all instances of your app across all the user's devices.

Categories : Android

Why does this mathematical operation work? (Getting 8-bit register from 32-bit register)
"mod 256" is the remainder after division by 256. In binary, this turns out to be the lowest 8 bits (because 256 is 2 to the 8th). This is just like "mod 2" gives you the least significant bit (0 or 1). On (in decimal, base 10), "mod 100" gives you the last two decimals ( 2013 mod 100 => 13).

Categories : Assembly

which one is better Generics or not Generics in Java?
You should almost never use the raw form in modern Java. There are a few places where it's hard not to, but in general it's a bad idea. Using the raw List and ArrayList types in your second snippet in no way prevents boxing - it just reduces type safety. In the generic version, you don't need the cast to int because the compiler knows that the list must only contain Integer references or null values; in the raw form there's no compile-time guarantee. There's nothing to stop you adding a completely different kind of reference - e.g. a string - to the list.

Categories : Java

MVC 4 and autofac: DependencyResolutionException
You need to register your controller without the .As<IController>() (or you need to use .AsSelf() but this is default setting). You need to this because the framework will try to resolve your Controller with using the concrete type HomeController and not the IController interface (so the RegisterControllers method register all the controller with .AsSelf() internally). So the following registration should work builder.Register( c => new HomeController( c.ResolveNamed<IRestClient>("Url1"), c.ResolveNamed<IRestClient>("Url2"))) .InstancePerLifetimeScope(); Note: you should have this call after the RegisterControllers call.

Categories : Asp Net Mvc

Autofac constrained binding
I can't think of any neat and concise implementation of such mechanism with Autofac, but maybe you can make use of one of Autofac's meanings of selecting implementation. I'd use keyed services, which in your case would look like this: first, instead of custom attributes you'd need to define an enum enum RepositoryKind {CacheNeeded, DataNeeded} then register components marking them with those that provide Cache or data functionality, for exaple like this: builder.RegisterType<DbRepository>() .Keyed<IRepository>(RepositoryKind.CacheNeeded); builder.Register(c => new CacheRepository(c.ResolveKeyed<IRepository(RepositoryKind.CacheNeeded))) .Keyed<IRepository>(RepositoryKind.DataNeeded); builder.Register(c => new HomeController(c.ResolveK

Categories : C#

Integrating Hyprlinkr with Autofac
You don't need to write you own IHttpControllerActivator because you can register the RouteLinker itself in the container. You just need the help of the RegisterHttpRequestMessage method which makes the HttpRequestMessage resolvable from the container. So your RouteLinker registration will look something like this: builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration); builder.Register(c => new RouteLinker(c.Resolve<HttpRequestMessage>())) .InstancePerApiRequest(); Now you can depend on the RouteLinker in your controllers: public MyController : ApiController { public MyController(RouteLinker routeLinker) { //do stuff with routeLinker } }

Categories : C#

How to reset autofac container?
Autofac by default overrides previous registrations with subsequent ones. That means you don't have to do anything special apart from updating container with your new instance: var builder = new ContainerBuilder(); builder.RegisterInstance(new Sample("A")).SingleInstance(); var container = builder.Build(); var sample = container.Resolve<Sample>(); // do your test ... // new test using same container var updater = new ContainerBuilder(); updater.RegisterInstance(new Sample("B")).SingleInstance(); updater.Update(container); // overwrites existing registrations var sample = container.Resolve<Sample>(); // returns "B"

Categories : Unit Testing

Replace factory with AutoFac
Short answer: Yes. Longer answer: First, in simple cases where a class Foo is registered as the implementation for IFoo, constructor parameters or properties of type Func<IFoo> will be resolved automatically by Autofac, with no additional wiring needed. Autofac will inject a delegate that basically executes container.Resolve<IFoo>() when invoked. In more complex cases like yours, where the exact concretion returned is based on input parameters, you can do one of two things. First, you can register a factory method as its return value to provide a parameterized resolution: builder.Register<IElement>((c, p) => { var dom= p.Named<IHtml>("dom"); switch (dom.ElementType) { case "table": return new TableElement(dom); case "div

Categories : C#

make autofac use TypeConverter
I dug through the autofac code and filed two issues about it: https://code.google.com/p/autofac/issues/detail?id=445 https://code.google.com/p/autofac/issues/detail?id=446

Categories : C#

property injection using autofac 3.1.1
The problem you have is Main method is static. Instanciate a class of Program and use is as non static class class Program { public ISodaService s { get; set; } static void Main(string[] args) { var resolver=SetUpContainer(); var instance=resolver.Resolve<Program>(); instance.Execute(args); } public void Execute(string[] args) { Console.Write(s.GetSoda()); Console.Read(); } private Autofac.IContainer void SetUpContainer() { var builder = new ContainerBuilder(); builder.RegisterType<Soda>().As<ISoda>(); builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired(); bui

Categories : C#

Autofac registered AuthorizationFilter calling twice
The line: builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration); will register anything that implements the IAutofacAuthorizationFilter interface. So strictly speaking, you shouldn't need the second line. The second line just re-registers what Autofac is already automatically doing in the line above. So, remove the second line.

Categories : C#

Autofac not finding the most greedy constructor
Problem was that my greedy -was- getting called .. but if u looked at the greedy-ctor, you'll see that i'm doing : this(). very lame newbie error. So it was calling the greedy ctor, but before it goes into scope, it has to bubble up to the other parameterless ctor. And I kept thinking it was skipping the greedy and just hitting the parameterless. Error Between User And Keyboard.

Categories : C#

Autofac ordered list as parameter
I have a solution, that is a combination of the IOrderedEnumerable, and the ResolveOrdered<TComponent> solution from the post I linked to above. Using the AutofacExtensions Class: public static class AutofacExtensions { private const string OrderString = "WithOrderTag"; private static int _orderCounter; public static IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> WithOrder<TLimit, TActivatorData, TRegistrationStyle>( this IRegistrationBuilder<TLimit, TActivatorData, TRegistrationStyle> registrationBuilder) { return registrationBuilder.WithMetadata(OrderString, Interlocked.Increment(ref _orderCounter)); } public static IOrderedEnumerable<TComponent> ResolveOrdered<TComponent>(this IComp

Categories : C#

Parameterless Controller Constructor Autofac
Hi i don't test that in VS 2010 because i don't have it. But in my VS 2013 works fine. public static class DependencyInjection { public static void Init() { // Create the container builder. var builder = new ContainerBuilder(); //Register controllers builder.RegisterControllers(Assembly.GetExecutingAssembly()); // Register other dependencies. builder.RegisterType<SessionStateProvider>().As<IStateProvider>().InstancePerHttpRequest(); // Build the container. var container = builder.Build(); //Configure ASP.NET MVC the dependency resolver DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } public

Categories : C#

Autofac dependency resolution error
Solution 1. You are registered a IDbContext as Named service. .Named<IDbContext>("Speed") Thus, you must use a ResolveNamed method. _container.ResolveNamed<IDbContext>("Speed"); Solution 2. You can just register a IDbContext as a type. In this case, the method Resolve() should work correctly. builder.Register<IDbContext>(c => new DbContext(ConfigurationManager.ConnectionStrings["Speed"].ConnectionString)) .InstancePerDependency();

Categories : C#

ASP.NET MVC. Autofac and multiple connection strings
One way to do it, is to create your own connection factory, and register it with autofac. Something like: interface IConnectionFactory{ SqlConnection CreateConnection(string connectionStringName); }

Categories : C#

Autofac, WebAPI, and Media Formatters
If you want to let Autofac to add your custom formatter to the marked controllers then you don't need to add it to the GlobalConfiguration.Configuration.Formatters because it makes your formatter globally available and it prevents Autofac to inject properties on it. So remove the GlobalConfiguration.Configuration.Formatters.Insert call and use the following exact syntax to register your formatter: builder.Register<MediaTypeFormatter>(c => new UserMediaFormatter()) .PropertiesAutowired() .InstancePerApiControllerType(typeof(UsersController));

Categories : Asp Net Web Api

Select multiple registrations for the same type in Autofac
You need to use NamedPropertyParameter instead of NamedParameter. builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>() .SingleInstance(); builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>() .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(UnauthorizedAccessException)), new NamedPropertyParameter("View", "UnauthorizedAccess") }) .SingleInstance(); builder.RegisterType<ErrorHandlerAttribute>().As<IExceptionFilter>() .WithProperties(new List<NamedPropertyParameter> { new NamedPropertyParameter("ExceptionType", typeof(NotImplementedException)), new NamedPropertyParameter("View", "UnderConstruction") }) .SingleInstance(); You also may as we

Categories : C#

Autofac Property Injection after a type is Registered
Use the WithProperty or WithProperties methods if you want to set the injections at registration rather than at initialization. ie builder.RegisterType(customType).WithProperty("PropertyName", "value");

Categories : C#

Having Automapper use services constructed by a Autofac with WebApi
This may or may not be suitable for you.. but here goes: We recently did this.. for model binders in MVC. Our model binders (on GET requests) now use Ninject-managed Services to build models. Basically, we inject a factory (using Ninject's Factories extension.. perhaps there is a similar one for Autofac) into an "AutomapperBootstrapper" class, which in turn creates Automapper mapping Profile's and adds them to Automapper. Somewhat like this: Mapper.Initialize(cfg => { cfg.AddProfile(_factory.CreateServiceViewModelMappingProfile()); // etc.. }); The mappings Profile's themselves use MapFrom(), which is evaluated each time a mapping occurs. Something like this: Mapper.CreateMap<Service, ServiceViewModel>() .ForMember(x => x.Regions, opt =

Categories : C#

how to create autofac factory for dependency resolution
public class DbContextFactory { private ILifetimeScope m_RootLifetimeScope; public DbContextFactory(ILifetimeScope rootLifetimeScope) { m_RootLifetimeScope = rootLifetimeScope; } public IDbContext CreateDbContext() { if (logic for selection first dbcontext) { return m_RootLifetimeScope.ResolveNamed<IDbContext>("first"); } else if (logic for selection second dbcontext) { return m_RootLifetimeScope.ResolveNamed<IDbContext>("second"); } else { throw new NotSupportedException(); } } } //registration builder.RegisterType<DbContextFactory>().SingleInstance(); //using var factory = yourContainer.Resolve<DbContextFactory>();

Categories : C#

FileNotFoundException when trying to load Autofac as an embedded assembly
Maybe the problem is how you try to load your EmbeddedAssembly. I have very small knowledge about how you can do it but i know the following example from code project works fine for me so maybe it will help you :-) Load DLL From Embedded Resource (If i misunderstand your question please tell me and i will delete my Answer)

Categories : C#

Registering NHibernate ISession as SingleInstance in Autofac
A session keeps track of all the entities and collections it has loaded or even referenced. Keeping a session open for all the lifetime of your app results in: Extremely high memory usage Extremely slow operations (scanning the list of loaded entities, which is done automatically by many operations, takes very long when there are too many) Impossibility to recover from errors, as the session state becomes corrupted when there is one

Categories : C#

Autofac attribute injection failing on attributes
Your property of type IDataAccessProvider has to be public for injection to work. You can still mark DebugLogAttribute, IDataAccessProvider and it's implementation as internal if you prefer. [DebugLogAttribute] public class HOmeController : Controller { public ActionResult Index() { return View(); } } internal class DebugLogAttribute : ActionFilterAttribute { public IDataAccessProvider DataAccess { get; set; } public override void OnActionExecuting(ActionExecutingContext filterContext) { Debugger.Break(); } public override void OnActionExecuted(ActionExecutedContext filterContext) { Debugger.Break(); } } internal interface IDataAccessProvider {} internal class DataAccessProvider:IDataAccessProvider {}

Categories : C#

Automapper & Autofac typeconverter - does not have a default constructor
You have three problems with your current code: You need to call ConstructServicesUsing before registering any mapping as described in the linked article: The tricky thing is we need to call that method before we register mapper classes. So the correct Mapper.Initialize is the follwing: Mapper.Initialize(map => { map.ConstructServicesUsing(t => container.Resolve(t)); map.CreateMap<long?, EntityToConvertTo>() .ConvertUsing<LongToEntity<NavigationFolder>>(); }); Because your LongToEntity<T> is an open generic you cannot use AsClosedTypesOf but you need to use here also the RegisterGeneric for the registration: So change your ITypeConverter<,> registration from: builder.Register

Categories : C#

Autofac configuring NHibernate ISession to allow null
I'm fairly sure you'd be better off when injecting singleton lifetime-scoped ISessionFactory instead of ISession. It means that there's one instance of ISessionFactory injected to each component, and each of those components creates its own ISession (or multiple ISessions if needed). As for the keywords check, by default NHibernate connects briefly to the database when building the ISessionFactory to check for reserved keywords (that's for schema/DDL creation). You can disable that, so the first connection to the database will be made on the first ISession use.

Categories : C#

Autofac - Mvc 5 beta - DependencyResolver fails to get type
OK I figured out how to replace DependencyResolver... this seems to be an anti pattern when constructor dependency is an option. I couldn't figure out how to make it work before but I gave it another go and looks like all you need is an IComponentContext constructor parameter and Autofac will take care of it by default: public class DefaultQueryBus : IQueryBus { private readonly IComponentContext componentContext; public DefaultQueryBus(IComponentContext componentContext) { this.componentContext = componentContext; } public IEnumerable<ValidationResult> Validate<TResult>(IQuery<TResult> query) { var handlerType = typeof(IQueryValidationHandler<,>).MakeGenericType(query.GetType(), typeof(TResult)); dynamic handler =

Categories : Asp Net

How can I disable or prevent Autofac from kicking in where it is unwanted?
Autofac chooses the constructor that has the most dependencies that it knows how to resolve. It seems that MyComponent is registered, but it is registered incorrectly: you have not specified what someNumber should be. In other words, if you just tried Resolve<MyComponent>() you would have the same problem - MyController is not the root issue here. There are a couple ways you could handle this. The easiest is to add a default constructor to MyComponent public MyComponent() : this(DateTime.Now.Millisecond) { } The second easiest is to adjust the MyComponent registration containerBuilder.Register(c => new MyComponent(DateTime.Now.Milliseconds)) .AsSelf(); You could also write the registration like this, to explicitly use the default constructor: containerBuilder.Register(

Categories : Asp Net Mvc

How do I create a Quartz.NET’s job requiring injection with autofac
The problem is that your AutofacJobFactory is not creating the ReleaseJob (you are doing this with JobBuilder.Create<ReleaseJob>() instead), so the IoC container is not aware of it's instantiation meaning dependency injection cannot occur. The following code should work: sched = schedFact.GetScheduler(); sched.JobFactory = new AutofacJobFactory(container); sched.Start(); // construct job info JobDetailImpl jobDetail = new JobDetailImpl("1Job", null, typeof(ReleaseJob )); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("1JobTrigger") .WithSimpleSchedule(x => x .RepeatForever() .WithIntervalInSeconds(5) ) .StartNow() .Build(); sched.ScheduleJob(jobDetail, trigger); Note that in this example we are not using JobBuilder.Create<Rel

Categories : Asp Net Mvc

Session service unique id initialization with Autofac
The problem is caused by your properties in the PushNotificationListener class. Since you create new lifetime scopes in their, within that scope a new SessionService will be created. Prevent doing this. Instead, there should only be one lifetime scope for each session. You should create a new lifetime scope (and only one lifetime scope) directly after the event is raised and before you resolve the root object. From that point on, all dependencies should be injected using constructor injection. This ensures that within that scope, there is only one SessionService.

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.