Search Results

Search found 3493 results on 140 pages for 'constructor'.

Page 16/140 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • Resolve dependency with autofac based on constructor parameter attribute

    - by Andrew Davey
    I'm using AutoFac. I want to inject a different implementation of a dependency based on an attribute I apply to the constructor parameter. For example: class CustomerRepository { public CustomerRepository([CustomerDB] IObjectContainer db) { ... } } class FooRepository { public FooRepository([FooDB] IObjectContainer db) { ... } } builder.Register(c => /* return different instance based on attribute on the parameter */) .As<IObjectContainer>(); The attributes will be providing data, such as a connection string, which I can use to instance the correct object. How can I do this?

    Read the article

  • StructureMap : How to define default constructor by code ?

    - by cik
    Hi, I can't figure out how to define the default constructor (when it exists overloads) for a type in StructureMap (version 2.5) by code. I want to get an instance of a service and the container has to inject a Linq2Sql data context instance into it. I wrote this in my 'bootstrapper' method : ForRequestedType<MyDataContext>().TheDefault.Is.OfConcreteType<MyDataContext>(); When I run my app, I got this error : StructureMap Exception Code: 202 No Default Instance defined for PluginFamily MyNamespace.Data.SqlRepository.MyDataContext, MyNamespace.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null If I comment out all Linq2Sql generated contructors that I don't need, it works fine. Update : Oh, and I forgot to say that I would not use the [StructureMap.DefaultConstructor] attribute.

    Read the article

  • constructor injection using Autofac 2 and Named Registration

    - by Thad
    I am currently attempting to remove a number of .Resolve(s) in our code. I was moving along fine until I ran into a named registration and I have not been able to get Autofac resolve using the name. What am I missing to get the named registration injected into the constructor. Registration builder.RegisterType<CentralDataSessionFactory>().Named<IDataSessionFactory>("central").SingleInstance(); builder.RegisterType<ClientDataSessionFactory>().Named<IDataSessionFactory>("client").SingleInstance(); builder.RegisterType<CentralUnitOfWork>().As<ICentralUnitOfWork>().InstancePerDependency(); builder.RegisterType<ClientUnitOfWork>().As<IClientUnitOfWork>().InstancePerDependency(); Current class public class CentralUnitOfWork : UnitOfWork, ICentralUnitOfWork { protected override ISession CreateSession() { return IoCHelper.Resolve<IDataSessionFactory>("central").CreateSession(); } } Would Like to Have public class CentralUnitOfWork : UnitOfWork, ICentralUnitOfWork { private readonly IDataSessionFactory _factory; public CentralUnitOfWork(IDataSessionFactory factory) { _factory = factory; } protected override ISession CreateSession() { return _factory.CreateSession(); } }

    Read the article

  • Error using traits class.: "expected constructor destructor or type conversion before '&' token"

    - by Mark
    I have a traits class that's used for printing out different character types: template <typename T> class traits { public: static std::basic_ostream<T>& tout; }; template<> std::ostream& traits<char>::tout = std::cout; template<> std::wostream& traits<unsigned short>::tout = std::wcout; gcc (g++) version 3.4.5 (yes somewhat old) is throwing an error: "expected constructor destructor or type conversion before '&' token" And I'm wondering if there's a good way to resolve this. (it's also angry about _O_WTEXT so if anyone's got some insight into that, I'd also appreciate it)

    Read the article

  • Boost::Interprocess Container Container Resizing No Default Constructor

    - by CuppM
    Hi, After combing through the Boost::Interprocess documentation and Google searches, I think I've found the reason/workaround to my issue. Everything I've found, as I understand it, seems to be hinting at this, but doesn't come out and say "do this because...". But if anyone can verify this I would appreciate it. I'm writing a series of classes that represent a large lookup of information that is stored in memory for fast performance in a parallelized application. Because of the size of data and multiple processes that run at a time on one machine, we're using Boost::Interprocess for shared memory to have a single copy of the structures. I looked at the Boost::Interprocess documentation and examples, and they typedef classes for shared memory strings, string vectors, int vector vectors, etc. And when they "use" them in their examples, they just construct them passing the allocator and maybe insert one item that they've constructed elsewhere. Like on this page: http://www.boost.org/doc/libs/1_42_0/doc/html/interprocess/allocators_containers.html So following their examples, I created a header file with typedefs for shared memory classes: namespace shm { namespace bip = boost::interprocess; // General/Utility Types typedef bip::managed_shared_memory::segment_manager segment_manager_t; typedef bip::allocator<void, segment_manager_t> void_allocator; // Integer Types typedef bip::allocator<int, segment_manager_t> int_allocator; typedef bip::vector<int, int_allocator> int_vector; // String Types typedef bip::allocator<char, segment_manager_t> char_allocator; typedef bip::basic_string<char, std::char_traits<char>, char_allocator> string; typedef bip::allocator<string, segment_manager_t> string_allocator; typedef bip::vector<string, string_allocator> string_vector; typedef bip::allocator<string_vector, segment_manager_t> string_vector_allocator; typedef bip::vector<string_vector, string_vector_allocator> string_vector_vector; } Then for one of my lookup table classes, it's defined something like this: class Details { public: Details(const shm::void_allocator & alloc) : m_Ids(alloc), m_Labels(alloc), m_Values(alloc) { } ~Details() {} int Read(BinaryReader & br); private: shm::int_vector m_Ids; shm::string_vector m_Labels; shm::string_vector_vector m_Values; }; int Details::Read(BinaryReader & br) { int num = br.ReadInt(); m_Ids.resize(num); m_Labels.resize(num); m_Values.resize(num); for (int i = 0; i < num; i++) { m_Ids[i] = br.ReadInt(); m_Labels[i] = br.ReadString().c_str(); int count = br.ReadInt(); m_Value[i].resize(count); for (int j = 0; j < count; j++) { m_Value[i][j] = br.ReadString().c_str(); } } } But when I compile it, I get the error: 'boost::interprocess::allocator<T,SegmentManager>::allocator' : no appropriate default constructor available And it's due to the resize() calls on the vector objects. Because the allocator types do not have a empty constructor (they take a const segment_manager_t &) and it's trying to create a default object for each location. So in order for it to work, I have to get an allocator object and pass a default value object on resize. Like this: int Details::Read(BinaryReader & br) { shm::void_allocator alloc(m_Ids.get_allocator()); int num = br.ReadInt(); m_Ids.resize(num); m_Labels.resize(num, shm::string(alloc)); m_Values.resize(num, shm::string_vector(alloc)); for (int i = 0; i < num; i++) { m_Ids[i] = br.ReadInt(); m_Labels[i] = br.ReadString().c_str(); int count = br.ReadInt(); m_Value[i].resize(count, shm::string(alloc)); for (int j = 0; j < count; j++) { m_Value[i][j] = br.ReadString().c_str(); } } } Is this the best/correct way of doing it? Or am I missing something. Thanks!

    Read the article

  • constructor in Perl with an array(OOPS)

    - by superstar
    whats the difference between these two 'new' constructors in perl? 1) sub new { my $class = shift; my $self = {}; $self->{firstName} = undef; $self->{lastName} = undef; $self->{PEERS} = []; bless ($self, $class); return $self; } 2) sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; bless $self, $class; return $self; } I am using the 2nd one so far, but i need to implement the arrays in perl? can you suggest a way to do it with the 2nd 'new' constructor

    Read the article

  • GWT UIBinding cannot find zero-arg constructor

    - by aarestad
    I'm trying my hand at the new GWT 2.0 UIBinder capability, and I have a ui XML that looks like this: <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:my='urn:import:com.mystuff.mypackage'> <g:VerticalPanel> <!-- other stuff --> <my:FileUploadPanel.ValidatingFileUpload styleName="field" ui:field="fileUpload" /> </g:VerticalPanel> ValidatingFileUpload is a non-static inner class contained in FileUploadPanel. It has an explicit zero-arg constructor that simply calls super(). However, when GWT starts up, I get this error: 00:00:18.359 [ERROR] Rebind result 'com.mystuff.mypackage.FileUploadPanel.ValidatingFileUpload' has no default (zero argument) constructors. java.lang.NoSuchMethodException: com.mystuff.mypackage.FileUploadPanel$ValidatingFileUpload.<init>() Any idea what might be going wrong here?

    Read the article

  • Invoke "internal extern" constructor using reflections

    - by Riz
    Hi, I have following class (as seen through reflector) public class W : IDisposable { public W(string s); public W(string s, byte[] data); // more constructors [MethodImpl(MethodImplOptions.InternalCall)] internal extern W(string s, int i); public static W Func(string s, int i); } I am trying to call "internal extern" constructor or Func using reflections MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static); object[] argVals = new object[] { "hi", 1 }; dynMethod.Invoke(null, argVals); and Type type = typeof(W); Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) }; ConstructorInfo cInfo = type.GetConstructor(BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, argTypes, null); object[] argVals = new object[] { "hi", 1 }; dynMethod.Invoke(null, argVals); unfortunantly both variants rise NullReferenceException when trying to Invoke, so, I must be doing something wrong?

    Read the article

  • Adding scope variable to an constructor

    - by Lupus
    I'm trying to create a class like architecture on javascript but stuck on a point. Here is the code: var make = function(args) { var priv = args.priv, cons = args.cons, pub = args.pub; return function(consParams) { var priv = priv, cons = args.cons; cons.prototype.constructor = cons; cons.prototype = $.extend({}, pub); if (!$.isFunction(cons)) { throw new Hata(100001); } return new cons(consParams); } }; I'm trying to add the priv variable on the returned function objects's scope and object scope of the cons.prototype but I could not make it; Here is the usage of the make object: var myClass = make({ cons: function() { alert(this.acik); }, pub: { acik: 'acik' }, priv: { gizli: 'gizli' } }) myObj = myClass(); PS: Please forgive my english...

    Read the article

  • Tuple struct constructor complains about private fields

    - by Grubermensch
    I am working on a basic shell interpreter to familiarize myself with Rust. While working on the table for storing suspended jobs in the shell, I have gotten stuck at the following compiler error message: tsh.rs:8:18: 8:31 error: cannot invoke tuple struct constructor with private fields tsh.rs:8 let mut jobs = job::JobsList(vec![]); ^~~~~~~~~~~~~ It's unclear to me what is being seen as private here. As you can see below, both of the structs are tagged with pub in my module file. So, what's the secret sauce? tsh.rs use std::io; mod job; fn main() { // Initialize jobs list let mut jobs = job::JobsList(vec![]); loop { /*** Shell runtime loop ***/ } } job.rs use std::fmt; pub struct Job { jid: int, pid: int, cmd: String } impl fmt::Show for Job { /*** Formatter ***/ } pub struct JobsList(Vec<Job>); impl fmt::Show for JobsList { /*** Formatter ***/ }

    Read the article

  • Microsoft Unity, parameters in constructor

    - by raffaeu
    I am using Unity with MVC and NHibernate. Unfortunately, our UnitOfWork resides in a different .dll and it doesn't have a default empty .ctor. This is what I do to register NHibernate: var connectionString = ConfigurationManager.ConnectionStrings["jobManagerConnection"].ConnectionString; var assemblyMap = ConfigurationManager.AppSettings["assemblyMap"]; container .RegisterType<IUnitOfWork, UnitOfWork>(new ContainerControlledLifetimeManager()); In my WebController I have this: /// <summary>Gets or sets UnitOfWork.</summary> [Dependency] public IUnitOfWork UnitOfWork { get; set; } The problem is that the constructor of UnitOfWork expects 2 mandatory strings. How I can setup the RegisterType for this Interface in order to pass the two parameters retreived from the web.config? Is it possible?

    Read the article

  • Constructor overriding

    - by demas
    I have a library with a class: class One def initialize puts "one initialize" end end I can not change the declaration and difinition of this class. I need create new class with my own constructor. Like this: class Two < One def initialize(some) puts some super end end one = One.new one = Two.new("thing") But when I launch code I got error: [[email protected]][~/temp]% ruby test.rb one initialize thing test.rb:10:in `initialize': wrong number of arguments (1 for 0) (ArgumentError) from test.rb:15:in `new' from test.rb:15:in `<main>'

    Read the article

  • Windows.Networking.EndpointPair constructor parameters

    - by ComFreek
    I want to create a new EndpointPair object: // hostname is a string // port is an integer var endpointPair = new Windows.Networking.EndpointPair(null, null, hostname, port); But I always get this error: 0x800a000d - JavaScript runtime error: Type mismatch I've already tried the following: converting port to a string passing "" instead of null for the first two Parameters. (null should be okay if the documentation here, under the section Remarks, is right) passing no Parameters, but that ends up in an "too few parameters" error message Above all, the documentation about the constructor has been removed (as of September 4, 2012): http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.endpointpair.endpointpair.aspx

    Read the article

  • Attribute class not calling constructor

    - by Coppermill
    I have created an Attribute, call MyAttribute, which is performing some security and for some reason the Constructor is not being fired, any reason why? public class Driver { // Entry point of the program public static void Main(string[] Args) { Console.WriteLine(SayHello1("Hello to Me 1")); Console.WriteLine(SayHello2("Hello to Me 2")); Console.ReadLine(); } [MyAttribute("hello")] public static string SayHello1(string str) { return str; } [MyAttribute("Wrong Key, should fail")] public static string SayHello2(string str) { return str; } } [AttributeUsage(AttributeTargets.Method)] public class MyAttribute : Attribute { public MyAttribute(string VRegKey) { if (VRegKey == "hello") { Console.WriteLine("Aha! You're Registered"); } else { throw new Exception("Oho! You're not Registered"); }; } }

    Read the article

  • how to deal a constructor with an array in Perl

    - by superstar
    whats the difference between these two 'new' constructors in perl? 1) sub new { my $class = shift; my $self = {}; $self->{firstName} = undef; $self->{lastName} = undef; $self->{PEERS} = []; bless ($self, $class); return $self; } 2) sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; bless $self, $class; return $self; } I am using the 2nd one so far, but i need to implement the arrays in perl? can you suggest a way to do it with the 2nd 'new' constructor and how can we use get and set methods on those array variables?

    Read the article

  • Factory Method pattern and public constructor

    - by H4mm3rHead
    Hi, Im making a factory method that returns new instances of my objects. I would like to prevent anyone using my code from using a public constructor on my objects. Is there any way of doing this? How is this typically accomplished: public abstract class CarFactory { public abstract ICar CreateSUV(); } public class MercedesFactory : CarFactory { public override ICar CreateSUV() { return new Mercedes4WD(); } } I then would like to limit/prevent the other developers (including me in a few months) from making an instance of Mercedes4WD. But make them call my factory method. How to?

    Read the article

  • Constructor invocation returned null: what to do?

    - by strager
    I have code which looks like: private static DirectiveNode CreateInstance(Type nodeType, DirectiveInfo info) { var ctor = nodeType.GetConstructor(new[] { typeof(DirectiveInfo) }); if(ctor == null) { throw new MissingMethodException(nodeType.FullName, "ctor"); } var node = ctor.Invoke(new[] { info }) as DirectiveNode; if(node == null) { // ???; } return node; } I am looking for what to do (e.g. what type of exception to throw) when the Invoke method returns something which isn't a DirectiveNode or when it returns null (indicated by // ??? above). (By the method's contract, nodeType will always describe a subclass of DirectiveNode.) I am not sure when calling a constructor would return null, so I am not sure if I should handle anything at all, but I still want to be on the safe side and throw an exception if something goes wrong.

    Read the article

  • Singleton constructor question

    - by gillyb
    Hi, I created a Singleton class in c#, with a public property that I want to initialize when the Singleton is first called. This is the code I wrote : public class BL { private ISessionFactory _sessionFactory; public ISessionFactory SessionFactory { get { return _sessionFactory; } set { _sessionFactory = value; } } private BL() { SessionFactory = Dal.SessionFactory.CreateSessionFactory(); } private object thisLock = new object(); private BL _instance = null; public BL Instance { get { lock (thisLock) { if (_instance == null) { _instance = new BL(); } return _instance; } } } } As far as I know, when I address the Instance BL object in the BL class for the first time, it should load the constructor and that should initialize the SessionFactory object. But when I try : BL.Instance.SessionFactory.OpenSession(); I get a Null Reference Exception, and I see that SessionFactory is null... why?

    Read the article

  • Constructor invokation returned null: what to do?

    - by strager
    I have code which looks like: private static DirectiveNode CreateInstance(Type nodeType, DirectiveInfo info) { var ctor = nodeType.GetConstructor(new[] { typeof(DirectiveInfo) }); if(ctor == null) { throw new MissingMethodException(nodeType.FullName, "ctor"); } var node = ctor.Invoke(new[] { info }) as DirectiveNode; if(node == null) { // ???; } return node; } I am looking for what to do (e.g. what type of exception to throw) when the Invoke method returns something which isn't a DirectiveNode or when it returns null (indicated by // ??? above). (By the method's contract, nodeType will always describe a subclass of DirectiveNode.) I am not sure when calling a constructor would return null, so I am not sure if I should handle anything at all, but I still want to be on the safe side and throw an exception if something goes wrong.

    Read the article

  • Is this class + constructor definition pattern overly redundant?

    - by Protector one
    I often come across a pattern similar to this: class Person { public string firstName, lastName; public Person(string firstName, string lastName) { this.firstName = firstName; this.lastName = lastName; } } This feels overly redundant (I imagine typing "firstName" once, instead of thrice could be enough…), but I can't think of a proper alternative. Any ideas? Maybe I just don't know about a certain design pattern I should be using here? Edit - I think I need to elaborate a little. I'm not asking how to make the example code "better", but rather, "shorter". In its current state, all member names appear 3 times (declaration, initialization, constructor arguments), and it feels rather redundant. So I'm wondering if there is a pattern (or semantic sugar) to get (roughly) the same behavior, but with less bloat. I apologize for being unclear initially.

    Read the article

  • python: calling constructor from dictionary?

    - by Jason S
    I'm not quite sure of the terminology here so please bear with me.... Let's say I have a constructor call like this: machineSpecificEnvironment = Environment( TI_C28_ROOT = 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000', JSDB = 'c:/bin/jsdb/jsdb.exe', PYTHON_PATH = 'c:/appl/python/2.6.4', ) except I would like to replace that by an operation on a dictionary provided to me: keys = {'TI_C28_ROOT': 'C:/appl/ti/ccs/4.1.1/ccsv4/tools/compiler/c2000', 'JSDB': 'c:/bin/jsdb/jsdb.exe', 'PYTHON_PATH': 'c:/appl/python/2.6.4'} machineSpecificEnvironment = Environment( ... what do I put here? it needs to be a function of "keys" ... ) How can I do this?

    Read the article

  • How to extract terms of specific data constructor from a list in Haskell

    - by finnsson
    A common problem I got in Haskell is to extract all terms in a list belonging to a specific data constructor and I'm wondering if there are any better ways than the way I'm doing it at the moment. Let's say you got data Foo = Bar | Goo , the list foos = [Bar, Goo, Bar, Bar, Goo] and wish to extract all Goos from foos. At the moment I usually do something like goos = [Goo | Goo <- foos] and all is well. The problem is when Goo got a bunch of fields and I'm forced to write something like goos = [Goo a b c d e f | Goo a b c d e f <- foos] which is far from ideal. How you do usually handle this problem?

    Read the article

  • Result of expression 'xxxx' is not a constructor in JS

    - by Pselus
    Trying to create an object in Javascript (for Appcelerator/Titanium). The "object" is defined like this: function server () { this.cacheimages = 0; this.login = ""; this.name = ""; this.root = ""; this.signup = ""; this.useimages = 0; this.userexists = ""; this.isdefault = 0; return this; } In the same file, in another function when I run this line: var server = new server(); I get the error Result of expression 'server' is not a constructor. I have tried it with and without the "return" line, neither work. What am I doing wrong?

    Read the article

  • How to deal with constructor argument names?

    - by Bane
    Say I have a class that has some properties, like x, y, width and height. In its constructor, I couldn't do this: class A { public: A(int, int, int, int); int x; int y; int width; int height; }; //Wrong and makes little sense name-wise: A::A(int x, int y, int width, int height) { x = x; y = y; width = width; height = height; } First of all, this doesn't really make sense. Second, x, y, width and height become some weird values (-1405737648) when compiled using g++. It does work, however, if I append "a" to the argument names. What is the optimal way of solving these naming conflicts?

    Read the article

  • Running a method after the constructor of any derived class

    - by Alexey Romanov
    Let's say I have a Java class abstract class Base { abstract void init(); ... } and I know every derived class will have to call init() after it's constructed. I could, of course, simply call it in the derived classes' constructors: class Derived1 extends Base { Derived1() { ... init(); } } class Derived2 extends Base { Derived2() { ... init(); } } but this breaks "don't repeat yourself" principle rather badly (and there are going to be many subclasses of Base). Of course, the init() call can't go into the Base() constructor, since it would be executed too early. Any ideas how to bypass this problem? I would be quite happy to see a Scala solution, too.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >