w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Unity register generic type for non generic interface
What am I missing? You are missing a factory. Think about it, there are no magic leprechauns working on the background guessing the type you need. You need to supply it. Either by explicitly stating what T is while configuring like this: container.RegisterType( typeof(IInterface), typeof(Class<SomeType>)); Or by creating a factory where you pass on the T at runtime: public interface IInterfaceFactory { IInterface Create<T>(); } The factory can be registered as follows: container.RegisterInstance<IInterfaceFactory>( new InterfaceFactory(container)); And an implementation can look as follows: public class InterfaceFactory : IInterfaceFactory { private readonly IUnityContainer container; public InterfaceFactory(IUnityContainer contain

Categories : C#

get properties using reflections for generic type object
Reflection on typeof(T) works fine; here's a simpler example based on yours, but (importantly) runnable. It outputs: ShopName TargetVehicleName code: using System; using System.Collections.Generic; public class CsvReport { public string ShopName { get; set; } public string TargetVehicleName { get; set; } } class ExportToCsv<T> { List<T> data; public ExportToCsv(List<T> obj) { data = obj; } public void WritePropNames() { foreach (var prop in typeof(T).GetProperties()) { Console.WriteLine(prop.Name); } } } static class Program { static void Main() { var obj = new List<CsvReport>(); obj.Add(new CsvReport { ShopName = "Foo", TargetVehicleName = "Bar" });

Categories : C#

Unity fails to load generic type definition via xml configuration
Try this instead of the [] notation <type type="Common.Utils.Logging.INLog`1, Common.Utils" mapTo="Common.Utils.Logging.NLog`1, Common.Utils" /> Feels awkward, I know, but it should work.

Categories : C#

Generic use of DropDownListFor with reflections
I haven't had time to try this out yet, but the stumbling block may be that the code is trying to bind PropertyInfo, not the actual property on the class. I would give this a shot: foreach (var property in Model.FormModel.GetType().GetProperties()) { @Html.DropDownListFor(m => property.Name, SelectList) }

Categories : C#

Unity container threw ResolutionFailedException when resolve open generic type
The open generic is registered with a mapping using the name "SQLRepo" but when resolved a name is not supplied so Unity cannot find the mapping. Try resolving by name: IRepository<string> rep = container.Resolve<IRepository<string>>("SQLRepo");

Categories : C#

Unity Register For One Interface Multiple Object and Tell Unity Where to Inject them
In the example below you have an interface implemented twice and injected on demand into two different client classes, just as you request. The trick is to use named registrations. class Program { static void Main(string[] args) { IUnityContainer container = new UnityContainer(); container.RegisterType<IFoo, Foo1>("Foo1"); container.RegisterType<IFoo, Foo2>("Foo2"); container.RegisterType<Client1>(new InjectionConstructor(new ResolvedParameter<IFoo>("Foo1"))); container.RegisterType<Client2>(new InjectionConstructor(new ResolvedParameter<IFoo>("Foo2"))); Client1 client1 = container.Resolve<Client1>(); Client2 client2 = container.Resolve<Client2>(); } } public interface IF

Categories : C#

ResolutionFailedException when register a Unity interceptor
The InnerException message says it all: Type 'DynamicModule.ns.Wrapped_ITestInterception_c8a0c8bf8a3d48a5b7f85924fab5711f' from assembly 'Unity_ILEmit_InterfaceProxies, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is attempting to implement an inaccessible interface. You need to make your interface public: public interface ITestInterception { void Test(); }

Categories : C#

How do I register components at run time with unity DI
First of all you need to register Unity configuration section. That looks like this: <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=2.1.505.0, Culture=neutral, PublickKeyToken=31bf3856ad364e35" /> This is Unity 2 configuration. Next is to add unity section. <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <!-- General aliases --> <alias alias="string" type="System.String, mscorlib" /> <alias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity, Version=2.1.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> <!-- Interface aliases --> <alias

Categories : C#

Check if a type implements a generic interface without considering the generic type arguments
As far as I know, the only way to do this is to get all interfaces and see if the generic definition matches the required interface type. bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Select(i => i.GetGenericTypeDefinition()) .Contains(typeof(MyInterface<,>)); EDIT: As Jon points out in the comments, you could also do: bool result1 = type.GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));

Categories : C#

Why isn't a generic type recognized as its derived type when passed as a generic parameter?
It is because you have list of Predicates. When you get element from list it is still only a base class. In runtime it will be a derived class, but generic works durring compilation.

Categories : C#

Generic Type x Generic Parameter: Building a "very generic" structure
Well, first of all, you're overcomplicating this. All you really need to do is: public void add(final Tree<? extends T> subTree) { Theres no need to parameterize add(). But anyways, I'll address your original attempt: You want SubTree extends Tree<Leaf>, because even if Leaf extends T you can't guarantee that SubTree extends Tree<T> with SubTree<Leaf> matches. E.g. if your class hierarchy is: public class Base { } public class A extends Base { } public class B extends Base { } If Leaf is A and SubTree is Tree<B> then add (final SubTree<Leaf>) does not match Tree<B>. So conceptually you actually want this: public <Leaf extends T, SubTree extends Tree<Leaf>> void add(final SubTree<Leaf> subTree) { Of course that is not va

Categories : Java

Register same Unity interception & call handler for all registered types
Unity 3 provides registration by convention which could help in this scenario: IUnityContainer container = new UnityContainer(); container.AddNewExtension<Interception>(); container.RegisterTypes( AllClasses.FromLoadedAssemblies().Where( t => t.Namespace == "My.Namespace.Services"), WithMappings.MatchingInterface, getInjectionMembers: t => new InjectionMember[] { new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<MyBehavior>() }); } You could combine the above with Policy Injection to use matching rules to wire up your call handler. That way you could use a variety of matching rules instead of (or in combination with) attributes to determine which call handlers go with which classes/methods. container

Categories : C#

What is the benefit of extending a generic by specifying the new type as actual type of generic
You might do something like this when dealing with recursive data structures. For example, nodes in a graph or a tree could be defined as a collection of other nodes: class Node extends AbstractList<Node> { ... } Equally you might see something like this if the abstract/generic type is meant for comparing objects of a similar type, such as is the case with java.lang.Comparable: class MyObject implements Comparable<MyObject> { public int compareTo(MyObject other) { ... } }

Categories : Java

Microsoft Unity - How to register connectionstring as a parameter to repository constructor when it can vary by client?
Quick assumption, you can use the host to identify your tenant. the following article has a slightly different approach http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/, its using NH, but it is usable. based on the above this hacked code may work (not tried/complied the following, not much of a unity user, more of a windsor person :) ) Container.RegisterType<IRequestMgmtRecipientRepository, RequestMgmtRecipientRepository>(new InjectionFactory(c => { //the following you can get via a static class //HttpContext.Current.Request.Url.Host, if i remember correctly var context = c.Resolve<HttpContextBase>(); var host = context.Request.Headers["Host"] ?? context.Request.Url.Host; var connStr =

Categories : C#

Open Generic types won't register in the catalog
Any idea what triggered it to start failing? Did you get a .NET update in that timeframe? Out of curiosity if you write a simple console app targeting .NET 4.5 does this issue repro? The reason I ask is I believe there was an update released for .NET 4.5 to make sure open generics didn't break existing .NET 4.0 apps and so if for some reason your tests are running in .NET 4.0 mode then then the open generic support will be disabled which could cause what you are seeing.

Categories : C#

Register all dependency injection for all generic repositories
You can make an open generic mapping: // using SimpleInjector.Extensions; container.RegisterOpenGeneric( typeof(IGenericRepository<,>), typeof(GenericRepository<,>)); The RegisterOpenGeneric extension method is located in the SimpleInjector.Extensions namespace of the core library. That will elegantly solve your problem.

Categories : C#

return generic IEnumerable when passing concrete type parameter for a generic method
You cannot convert the Type class to a generic T parameter without using reflection. The parameter also needs to be present as part of the method. Jon Skeet was using type inference by example combined with generics in order to guarantee type safety and simplify the generic code. Unfortunately you will lose that type safety using Type and reflection. private IEnumerable<EntityObject> GetFilteredData(Type entityType, SortedList<string, string> filterList, List<int> weeks) { var method = typeof(<class>).GetMethod("GetFilteredDataImpl"); var generic = method.MakeGenericMethod(entityType); return (IEnumerable<EntityObject>)generic.Invoke(this, new[] {

Categories : C#

How to realize explicit and implicit type conversion for non-generic synonyms of generic struct?
The error User-defined conversion must convert to or from the enclosing type. means that your conversion operators need to convert to/from A<T>. Yours are converting to/from A<int/string>. That's not the same thing (much less general at least). So this cannot work. You have to find some other way to do the conversions. Maybe runtime casting can help here (define the operators as acting on A<T> and do casting inside of them). I think this problem is unrelated to the type synonyms. In fact they made the question harder to understand.

Categories : C#

Late-Binding Exception Calling Generic Method of Generic Type in C#
Your GetFirstGenericArgument() is wrong. Calling GetGenericTypeDefinition() returns the underlying open generic type. Its type argument is T. Instead, you should write t.GetGenericArguments()[0], which will get the value of the generic type parameter for the closed type. No; your code doesn't make any sense. What on earth are you trying to do? I suspect that you actually want to write public class CollectionHandler<T> { public void Handle(IEnumerable<T> collection) { // Look ma, no reflection! } }

Categories : C#

How to declare a const field of a generic value type provided as generic argument
Type parameter is not allowed for constant type. Because a struct cannot be made const (from C# specification 10.4 Constants) The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. A kind of workaround to this limitation is to declare it as static readonly. public static readonly ValueType val = default(ValueType);

Categories : C#

Reflection - Navigate a non-generic method from a generic type definition to a concrete one
You can use the MakeGenericType method, like this: m.DeclaringType.MakeGenericType(typeof(int)) and then probably GetMethod again if you really want to go this way: m.DeclaringType.MakeGenericType(typeof(int)).GetMethod("Method"); However, consider Jon Skeet's comment for simpler solution.

Categories : C#

How can i make a generic function of two functions with a generic type specifier to a parameter
public class BinarySearchComparers<T> : IComparer<KeyValuePair<int, T>> // Declares a generic type { public int Compare(KeyValuePair<int, T> x, KeyValuePair<int, T> y) { return x.Key.CompareTo(y.Key); } } Is it what you want? Update Given Chris Sinclair understanding of your question, the solution might be: public class BinarySearchComparers<U, T> : IComparer<KeyValuePair<U, T>> // Declares a generic type where U : IComparable<U> // Restricts the type U to implémentations of IComparable<U> (necessary to call CompareTo) { public int Compare(KeyValuePair<U, T> x, KeyValuePair<U, T> y) { return x.Key.CompareTo(y.Key); } }

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#

Type Erasure - Extending Java Generic Class To Be Non-Generic
Yes, IntegerList is a reified type, which is what I think you're trying to say. And while we are at it, ArrayList is also a reified type, which means you can do the same things with ArrayList that you can do with IntegerList. (But not with ArrayList<Integer>, which is not a reified type.)

Categories : Java

Create instance of generic type in Java within the generic class
Due to implementation of generics in Java you must pass the Class<T> object for the further use. Here is the example: public class Outer<E> { private static class Inner<E> { E createContents(Class<E> clazz) { try { return clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { return null; } } } private Class<E> clazz; private Inner<E> inner; public Outer(Class<E> clazz) { this.clazz = clazz; this.inner = new Inner<>(); } public void doSomething() { E object = inner.createContents(clazz); System.out.println(object); } } Also you can use <? extends E>, p

Categories : Java

Modifying value type in generic class implementing generic interface C#
You are trying to add 10 (an integer) to a value of type T. T can be an integer, or a DateTime, or a List, or some other custom class. This means that there is absolutely no guarantee that your T will be able to add itself to an integer. Unfortunately, there is no way in C# to add a generic type constraint that will restrict the parameter to a type that will support a certain operation. There are workaround, but they are ugly. i.e. you could have: class Point<T>{ ... } and then have class IntPoint : Point<int>, IDoable<int> { ... } class DoublePoint : Point<double>, IDoable<Double> { ... }

Categories : C#

Casting between an object of generic type "T" and an object of generic type ">"
Based on the exception, it looks like you're initializing element with new Object[someLength] and doing an unchecked cast to T[]. This is likely happening in ArrayLinearList. The problem is that in this code: element[ pedro ] = maria; element is treated as a Comparable[] at runtime, and an Object[] isn't a Comparable[]. There are many existing posts related to generic array creation, but your issue is interesting because you've thrown inheritance into the mix (with a narrowing of a type parameter's bounds). The best solution seems to be only interacting with element within the ArrayLinearList class. Make it private and expose getters and setters. This should avoid runtime failures like this (which take some thought to avoid when doing unchecked casts like (T[])new Object[someLength]).

Categories : Java

Unity 3 and Error "The type name or alias "xxxxx" could not be resolved. Please check your configuration file and verify this type name."
The problem is in you config file. You are mixing two concepts with some incorrect syntax. The <assembly... /> and <namespace ... /> nodes provide an assembly and namespace search order when your <register ... /> node contains a type that cannot be found by itself. If a type cannot be found, it searches through all combinations of [namespace].Type, [assembly]. Here's where the error is: it does NOT search for Type, [assembly]. If any <namespace ... /> nodes are defined, it does NOT try appending only the assembly. So your <register type="Biblioteca.Contracts.IManterCategoriaBO" mapTo="Biblioteca.Business.ManterCategoriaBO" /> node has the type Biblioteca.Contracts.IManterCategoriaBO which does not contain the assembly, so it cannot be found. Therefore,

Categories : C#

Can I pass a generic into a non-generic function once I've checked its type?
The fact that you check the dynamic type of the variable doesn't change its static type, and that what it's used to check the call. If you want to do that, you need a cast. You can use a checked cast to do it in one go: Enumerable ex = x as Enumerable; if (ex != null && !EnumerableContainsEnumerable(ex, b)) return false; The as operator checks whether the cast is possible: if it is it will return the casted object; if it is not, it will return null.

Categories : C#

Generic type conversion in generic method
You seem to hope that the class called NetworkEventBase<T> would be covariant in T. But generic classes can't be covariant in C# (generic interfaces can). See other threads on this issue.

Categories : C#

Deriving generic type from generic ArrayList
This declaration public class BuyersGuideResponse<BuyersGuideItem> extends ArrayListResponse is equivalent to public class BuyersGuideResponse<T> extends ArrayListResponse so you can see why that wouldn't work. It would try to do add(new T(nodes.item(i))); The type parameter is shadowing the name of the type. I would do the following public class ArrayListResponse<T> extends ArrayList<T> for your parent class. public class BuyersGuideResponse extends ArrayListResponse<BuyersGuideItem> for your child implementation. Here BuyersGuideItem is a type argument and won't hide the type name.

Categories : Java

How To Cast Generic List of One Type To Generic List of an Unknown Type
If you know that each item in the list is of type ObjectType, you can do this: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<int> resultList = sourceList.Cast<int>().ToList(); If you actually want to convert each item in the list in a generic way, the simplest way would be to do something like this: public static IEnumerable<T> ConvertTo<T>(this IEnumerable items) { return items.Cast<object>().Select(x => (T)Convert.ChangeType(x, typeof(T))); } This would be implemented as an extension method, so you can write: List<object> sourceList = new List<object>() { 1, 2, 3 }; List<string> resultList = sourceList.ConvertTo<string>().ToList(); If the target type isn't known at compile-time, you would i

Categories : C#

Generic type constraint on generic type
That's not possible. You have to include TChannel as a generic type parameter of Proxy. One of the options to get over this “limitation” (in quotes because it is a by-design feature that arises from how the C# type system works) is to use an interface which each channel would be supposed to implement: public interface IChannel { … } public class Proxy<TClient>() where TClient : ClientBase<IChannel> { } public class MyObscureChannel : IChannel { … } public class MyObscureClient : ChannelBase<MyObscureChannel> { … } … var client = new Proxy<MyObscureClient>(…); // MyObscureChannel is implied here

Categories : C#

Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?
Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type? A is a raw type. That's a type with all generics dropped in the API dropped, even ones with fixed type arguments. See the JLS section 4.8 and the Raw Types section of the Java Generics FAQ for more information. In this case, if you want any A, you can use a wildcard: public static void test(A<?> i)

Categories : Java

Non-generic object of generic type
Then why compiler is raising warning of unchecked or unsafe operation for second piece of code? Because you're assigning an ArrayList to a variable with type ArrayList<String>. That means that while the compiler will enforce the expectation that the array list will only contain strings when you reference that list through ar, it can't be sure that you don't have other references to the non-parameterized ArrayList that you'll use to add non-strings to it, like this: ArrayList anythingGoes = new ArrayList(); ArrayList<String> onlyStrings = anythingGoes; // Unchecked/unsafe op anythingGoes.add(new Date()); for (String s : onlyStrings) { // Blows up // ... }

Categories : Java

How to make Generic Type as out type if it is reference Type?
If you have an error with the return type of IEnumerable<IGrouping<string, MyClass>> in a generic class that has been declared using <T>, then I'm guessing that your return type should actually be IEnumerable<IGrouping<string, T>>... of course, without seeing your code, this can only be a guess.

Categories : C#

Create instance of generic type in Java when parameterized type passes through hierarchies?
getClass().getGenericSuperclass(); gives you the details of the super class. Therefore it will only work if you subclass a parameterized super class. It won't work if you instantiate a parameterized super class given type parameters.

Categories : Java

Java Pass instance type of Object to generic class type parameter
No.. generic type should be known at compile time. Generics are there to catch possible runtime exceptions at compile time itself. List<Integer> list = new ArrayList<Integer>(); //..some code String s = list.get(0); // this generates compilation error because compiler knows that list is meant to store only Integer objects and assigning the value got from list to String is definitely an error. If the generic type was determined at run-time this would have been difficult.

Categories : Java

Create instance of generic type in Java when parameterized type is contained?
The anonymous class must have the actual type parameter hard-coded in its declaration for it to work. new Parameterized<E>(){}; does not work. You are just hard-coding "E" (a type variable). So when you look at the metadata using reflection all you see is "E" (a type variable). You must create a subclass which hard-codes its superclass with an actual class as type argument at compile-time: new Parameterized<String>(){}; I tried to adapt Steve B's approach of creating an anonymous subclass: You missed the whole point of that. The point was not to create a subclass. The point was to create a subclass with the actual class of the type argument hard-coded in the superclass.

Categories : Java

How to return correct type from generic function passed a related abstract type parameter
I am just going to reiterate my own (current) "answer" for my question, because I thought it would be interesting/instructive to allow readers to vote it up or down to generate a more direct comparison with answers provided by others. trait Context { // ... other stuff ... protected val aList: List[A] protected val bList: List[B] protected val cList: List[C] def get[R <: Referenced](ref: R#refType): Option[R] = { val result = ref match { case aRef: ARef => aList.find(_.ref == aRef) case bRef: BRef => bList.find(_.ref == bRef) case cRef: CRef => cList.find(_.ref == cRef) case _ => throw new RuntimeException("Unknown Ref type for retrieval: "+ref) } result.asInstanceOf[Option[R]] } }

Categories : Scala



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