Search Results

Search found 3300 results on 132 pages for 'dependency walker'.

Page 30/132 | < Previous Page | 26 27 28 29 30 31 32 33 34 35 36 37  | Next Page >

  • Unity Framework constructor parameters in MVC

    - by ubersteve
    I have an ASP.NET MVC3 site that I want to be able to use different types of email service, depending on how busy the site is. Consider the following: public interface IEmailService { void SendEmail(MailMessage mailMessage); } public class LocalEmailService : IEmailService { public LocalEmailService() { // no setup required } public void SendEmail(MailMessage mailMessage) { // send email via local smtp server, write it to a text file, whatever } } public class BetterEmailService : IEmailService { public BetterEmailService (string smtpServer, string portNumber, string username, string password) { // initialize the object with the parameters } public void SendEmail(MailMessage mailMessage) { //actually send the email } } Whilst the site is in development, all of my controllers will send emails via the LocalEmailService; when the site is in production, they will use the BetterEmailService. My question is twofold: 1) How exactly do I pass the BetterEmailService constructor parameters? Is it something like this (from ~/Bootstrapper.cs): private static IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType<IEmailService, BetterEmailService>("server name", "port", "username", "password"); return container; } 2) Is there a better way of doing that - i.e. putting those keys in the web.config or another configuration file so that the site would not need to be recompiled to switch which email service it was using? Many thanks!

    Read the article

  • Ninject with Object Initializers and LINQ

    - by Alexander Kahoun
    I'm new to Ninject so what I'm trying may not even be possible but I wanted to ask. I free-handed the below so there may be typos. Let's say I have an interface: public interface IPerson { string FirstName { get; set; } string LastName { get; set;} string GetFullName(); } And a concrete: public class Person : IPerson { public string FirstName { get; set; } public string LastName { get; set; } public string GetFullName() { return String.Concat(FirstName, " ", LastName); } } What I'm used to doing is something like this when I'm retrieving data from arrays or xml: public IEnumerable<IPerson> GetPeople(string xml) { XElement persons = XElement.Parse(xml); IEnumerable<IPerson> people = ( from person in persons.Descendants("person") select new Person { FirstName = person.Attribute("FName").Value, LastName = person.Attribute("LName").Value }).ToList(); return people; } I don't want to tightly couple the concrete to the interface in this manner. I haven't been able to find any information in regards to using Ninject with LINQ to Objects or with object initializers. I may be looking in the wrong places, but I've been searching for a day now with no luck at all. I was contemplating putting the kernel into an singleton instance and seeing if that would work, but I'm not sure that it will plus I've heard that passing your kernel around is a bad thing. I'm trying to implement this in a class library currently. If this is not possible, does anyone have any examples or suggestions as to what the best practice is in this case? Thanks in advance for the help. EDIT: Based on some of the answers I feel I should clarify. Yes, the example above appears short lived but it was simply an example of one piece that I was trying to do. Let's give a bigger picture. Say instead of XML I am gathering all my data through a 3rd party web service and I'm creating an interface for it, the data could be a defined object in the wsdl or it could sometimes be an xml string. IPerson could be used for both the Person object and a User object. I will be doing this inside of a separate class library, because it needs to be portable and will be used in other projects, and handing it to an MVC3 Web Application and the objects will be used in javascript as well. I appreciate all the input so far.

    Read the article

  • Picking Up Repositories With Structuremap

    - by alphadogg
    I am not sure how to use StructureMap to scan for all repositories in a particular namespace. Most repositories take the form: namespace CPOP.Infrastructure.Repositories { public class PatientRepository : LinqRepository<Patient>, IPatientRepository { } } namespace CPOP.Infrastructure.Repositories { public class LinqRepository<T> : Repository<T>, ILinqRepository<T> { } } namespace CPOP.Domain.Contracts.Repositories { public interface IPatientRepository : ILinqRepository<Patient> { } } I tried: x.Scan(scanner => { scanner.Assembly(Assembly.GetExecutingAssembly()); scanner.ConnectImplementationsToTypesClosing(typeof(ILinqRepository<>)); }) But, it only picks up the LinqRepository class. What's the best way to pick up the various repositories I'll be dumping in there?

    Read the article

  • Unity IoC and MVC modelbinding

    - by danielovich
    Is it ok to have a static field in my controller for my modelbinder to call ? Eg. public class AuctionItemsController : Controller { private IRepository<IAuctionItem> GenericAuctionItemRepository; private IAuctionItemRepository AuctionItemRepository; public AuctionItemsController(IRepository<IAuctionItem> genericAuctionItemRepository, IAuctionItemRepository auctionItemRepository) { GenericAuctionItemRepository = genericAuctionItemRepository; AuctionItemRepository = auctionItemRepository; StaticGenericAuctionItemRepository = genericAuctionItemRepository; } internal static IRepository<IAuctionItem> StaticGenericAuctionItemRepository; here is the modelbinder public class AuctionItemModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (AuctionItemsController.StaticGenericAuctionItemRepository != null) { AuctionLogger.LogException(new Exception("controller is null")); } NameValueCollection form = controllerContext.HttpContext.Request.Form; var item = AuctionItemsController.StaticGenericAuctionItemRepository.GetSingle(Convert.ToInt32(controllerContext.RouteData.Values["id"])); item.Description = form["title"]; item.Price = int.Parse(form["price"]); item.Title = form["title"]; item.CreatedDate = DateTime.Now; item.AuctionId = 1; //TODO: Stop hardcoding this item.UserId = 1; return item; }} i am using Unity as IoC and I find it weird to register my modelbinder in the IoC container. Any other good design considerations I shold do ?

    Read the article

  • Binding a Value from a View-Model to the View-Model of a child User Control in Silverlight?

    - by andrej351
    Hi there, So i have a UserControl for one of my Views and have another 'child' UserControl inside that. The outer 'parent' UserControl has a Collection on its View-Model and a Grid control on it to display a list of Items. I want to place another UserControl inside this UserControl to display a form representing the details of one Item. The outer / parent UserControl's View-Model already has a property on it to hold the currently selected Item and i would like to bind this to a DependancyProperty on the inner / child UserControl. I would then like to bind that DependancyProperty to a property on the child UserControl's View-Model. I can then set the DependancyProperty once in XAML with a binding expression and have the child UserControl do all its work in its View-Model like it should. The code i have looks like this.. Parent UserControl: <UserControl x:Class="ItemsListView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel}"> <!-- Grid Control here... --> <ItemDetailsView Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemsListViewModel.SelectedItem}" /> </UserControl> Child UserControl: <UserControl x:Class="ItemDetailsView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel}" ItemDetailsView.Item="{Binding Source={StaticResource ServiceLocator}, Path=ItemDetailsViewModel.Item, Mode=TwoWay}"> <!-- Form controls here... --> </UserControl> The selected Item is bound to the DependancyProperty fine. However from the DependancyProperty to the child View-Model does not. I've used this sort of apporach in a WPF app without problems. It appears to be a situation where there are two concurrent bindings which need to work but with the same target for two sources. Why won't the second (in the child UserControl) binding work?? Is there a way to acheive the behaviour I'm after?? Cheers.

    Read the article

  • How to do manual DI with deep object graphs and many dependencies properly

    - by Fabian
    I believe this questions has been asked in some or the other way but i'm not getting it yet. We do a GWT project and my project leader disallowed to use GIN/Guice as an DI framework (new programmers are not going to understand it, he argued) so I try to do the DI manually. Now I have a problem with deep object graphs. The object hierarchy from the UI looks like this: AppPresenter-DashboardPresenter-GadgetPresenter-GadgetConfigPresenter The GadgetConfigPresenter way down the object hierarchy tree has a few dependencies like CustomerRepository, ProjectRepository, MandatorRepository, etc. So the GadgetPresenter which creates the GadgetConfigPresenter also has these dependencies and so on, up to the entry point of the app which creates the AppPresenter. Is this the way manual DI is supposed to work? doesn't this mean that I create all dependencies at boot time even I don't need them? would a DI framework like GIN/Guice help me here?

    Read the article

  • StrcutureMap Wiring - Sanity Check Please

    - by Steve Ward
    Hi - Im new to IOC and StructureMap and have an n-level application and am looking at how to setup the wirings (ForRequestedType ...) and just want to check with people with more experience that this is the best way of doing it! I dont want my UI application object to reference my persistence layer directly so am not able to wire everything up in this UI project. I now have it working by defining a Registry class in each project which wires up the types in the project as needed. The layer above registers its types and also calls the assembly below and looks for registries so that all types are registered throught the hierrachy. E.g. I have UI, Service, Domain, and Persistence libraries. In my service layer the registry looks like Scan(x => { x.Assembly("MyPersistenceProject"); x.LookForRegistries(); }); ForRequestedType<IService>().TheDefault.Is.OfConcreteType<MyService>(); Is this a recommended way of doing this in a setup such as this? Are there better ways and what are the advantages / disadvantages of these approaches in this case?

    Read the article

  • Inject same DataContext instance across several types with Unity

    - by Sergejus
    Suppose I have IRepository interface and its implementation SqlRepository that takes as an argument LINQ to SQL DataContext. Suppose as well that I have IService interface and its implementation Services that takes three IRepository, IRepository and IRepository. Demo code is below: public interface IRepository<T> { } public class SqlRepository<T> : IRepository<T> { public SqlRepository(DataContext dc) { ... } } public interface IService<T> { } public class Service<T,T1,T2,T3> : IService<T> { public Service(IRepository<T1> r1, IRepository<T2>, IRepository<T3>) { ... } } Is it any way while creating Service class to inject all three repositories with the same DataContext?

    Read the article

  • How to execute an Ant task only when source files have been modified?

    - by hughalexb
    There must be an easy way to do this. I build a Flex app using ant that depends on a SWC library, which works fine except that it rebuilds the library whether it needs to or not. How do I tell ant to only run the task if any of the sources files of the library (*.as, *.mxml) are newer than the SWC? I've looked at <dependset but it only seems to delete files, not determine whether a task should be run or not. <depend seems to expect a one-to-one relationship between the source and target files rather than a one-to-many relationship -- I have many input files and one output file, but no intermediate object files. Thanks a lot, Alex

    Read the article

  • Inject filter into Zend_View

    - by chelmertz
    Hi! I wish to set some properties in MyFilter with constructor injection but it seems impossible with Zend_View::addFilter(string $filter_class_name) since it loads a new instance upon usage. MyFilter implements Zend_Filter_Interface. Can I somehow inject an instance of a filter to an instance of Zend_View?

    Read the article

  • Why JPA injection not works on @PersistentUnit

    - by Dewfy
    Hello colleagues! It is continues of question ( http://stackoverflow.com/questions/2570976/struts-2-bean-is-not-created ) I'm using struts2 + toplink in my very simple web application under Tomcat. On the page I would like use iteration tag. That is why I've declared some factory (SomeFactory) that resolves collection of entities (Entity). Per article: http://download-uk.oracle.com/docs/cd/B32110_01/web.1013/b28221/usclient005.htm#CIHCEHHG the only thing I need is declaration: @PersistenceContext(unitName="name_in_persistence_xml") public class SomeFactory { @PersistenceUnit(unitName="name_in_persistence_xml") EntityManagerFactory emf; public EntityManager getEntityManager() { assert(emf != null); //HERE every time it is null return emf.createEntityManager(); } public Collection<Entity> getAll() { return getEntityManager().createNamedQuery("Entity.findAll").getResultList(); } } What is wrong? May be i miss something in web.xml? How to pre-init toplink for web application to allow injection happen?

    Read the article

  • Using StructureMap to create classes by a name?

    - by Bevan
    How can I use StructureMap to resolve to an appropriate implementation of an interface based on a name stored in an attribute? In my project, I have many different kinds of widgets, each descending from IWidget, and each decorated with an attribute specifying the kind of associated element. To illustrate: [Configuration("header")] public class HeaderWidget : IWidget { } [Configuration("linegraph")] public class LineGraphWidget : IWidget { } When processing my (XML) configuration file, I want to obtain an instance of the appropriate concrete class based on the name of the element I'm processing. public IWidget CreateWidget(XElement definition) { var kind = definition.Name.LocalName; var widget = // What goes here? widget.Configure(definition); return widget; } Each definition should result in a different widget being created - I don't need or want the instances to be shared. In the past I've written plenty of code to do this kind of thing manually, including writing a custom "roll-your-own" IoC container for one project. However, one of my goals with this project is to become proficient with StructureMap instead of reinventing the wheel. I think I've already managed to set up automatic scanning of assemblies so that StructureMap knows about all my IWidget implementations: public class WidgetRegistration : Registry { public WidgetRegistration() { Scan( scanner => { scanner.AssembliesFromApplicationBaseDirectory(); scanner.AddAllTypesOf<IWidget>(); }); } } However, this isn't registering the names of my widgets with StructureMap. What do I need to add to make my scenario work? (While I am trying to use StructureMap in this project, an answer showing me how to solve this problem with a different DI/IoC tool would still be valuable.)

    Read the article

  • Intermittent "Specified cast is invalid" with StructureMap injected data context

    - by FreshCode
    I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my repository layer when performing an abstracted SELECT query mapped with LINQ. The error can't be caused by a mismatched database schema since it works intermittently and it's on my local dev machine. Could it be because StructureMap is caching the data context between page requests? If so, how do I tell StructureMap v2.6.1 to inject a new data context argument into my repository for each request? Update: I found this question which correlates my hunch that something was being re-used. Looks like I need to call Dispose on my injected data context. Not sure how I'm going to do this to all my repositories without copypasting a lot of code. Edit: These errors are popping up all over the place whenever I refresh my local machine too quickly. Doesn't look like it's happening on my remote deployment box, but I can't be sure. I changed all my repositories' StructureMap life cycles to HttpContextScoped() and the error persists. Code: public ActionResult Index() { // error happens here, which queries my page repository var page = _branchService.GetPage("welcome"); if (page != null) ViewData["Welcome"] = page.Body; ... } Repository: GetPage boils down to a filtered query mapping in my page repository. public IQueryable<Page> GetPages() { var pages = from p in _db.Pages let categories = GetPageCategories(p.PageId) let revisions = GetRevisions(p.PageId) select new Page { ID = p.PageId, UserID = p.UserId, Slug = p.Slug, Title = p.Title, Description = p.Description, Body = p.Text, Date = p.Date, IsPublished = p.IsPublished, Categories = new LazyList<Category>(categories), Revisions = new LazyList<PageRevision>(revisions) }; return pages; } where _db is an injected data context as an argument, stored in a private variable which I reuse for SELECT queries. Error: Specified cast is not valid. Exception Details: System.InvalidCastException: Specified cast is not valid. Stack Trace: [InvalidCastException: Specified cast is not valid.] System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539 System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500 System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50 System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383 Manager.Controllers.SiteController.Index() in C:\Projects\Manager\Manager\Controllers\SiteController.cs:68 lambda_method(Closure , ControllerBase , Object[] ) +79 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39 System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709 System.Web.Mvc.Controller.ExecuteCore() +162 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58 System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371

    Read the article

  • How can I bind another DependencyProperty to the IsChecked Property of a CheckBox?

    - by speedmetal
    Here's an example of what I'm trying to accomplish: <Window x:Class="CheckBoxBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel> <CheckBox Name="myCheckBox">this</CheckBox> <Grid> <Grid.Resources> <Style TargetType="ListBox"> <Style.Triggers> <Trigger Property="{Binding ElementName=myCheckBox, Path=IsChecked}" Value="True"> <Setter Property="Background" Value="Red" /> </Trigger> </Style.Triggers> </Style> </Grid.Resources> <ListBox> <ListBoxItem>item</ListBoxItem> <ListBoxItem>another</ListBoxItem> </ListBox> </Grid> </StackPanel> </Window> When I try to run it, I get this XamlParseException: A 'Binding' cannot be set on the 'Property' property of type 'Trigger'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. So how can I bind a property on the ListBox to the IsChecked property of a CheckBox?

    Read the article

  • Inject WCF proxy with credentials using StructureMap

    - by Steve Horn
    I have a service proxy generated by svcutil which generated an interface(IStudentContract) and a concrete type implementing (StudentContractClient). I'd like to have instances of StudentContractClient injected into my classes via StructureMap. My proxy also needs to have credentials supplied as seen in this passing unit test: <Test()> _ Public Sub Then_the_web_service_call_should_not_throw_an_exception() Dim studentServiceProxy As New StudentContractClient Dim credential As New NetworkCredential credential.Domain = ConfigurationManager.AppSettings("something") credential.UserName = ConfigurationManager.AppSettings("something") credential.Password = ConfigurationManager.AppSettings("something") studentServiceProxy.ClientCredentials.Windows.ClientCredential = credential Dim result = studentServiceProxy.GetCurrentTeachersByStudentSepid(26899) result.Count.ShouldEqual(4) End Sub My question is what would the structuremap configuration look like to have instances of IStudentContract injected with the credentials supplied? Thanks for any help!

    Read the article

  • Detecting type of webserive in httpmodule

    - by Marcus
    Hi, Is there any way to detect the type of a webservice inside a httpmodule? The reason for this is that I want to do some property injection to the webservice before it's processed. I found this: http://social.msdn.microsoft.com/Forums/en/asmxandxml/thread/0e848eee-d353-4e67-b47f-89fddb600009 but that is one h..l of an ugly solution. Anyone have a nice solution?

    Read the article

  • WPF custom DependencyProperty notify changes

    - by morsanu
    Hey guys I have a class called MyComponent and it has a DependencyProperty caled BackgroundProperty. public class MyComponent { public MyBackground Background { get { return (MyBackground)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } public static readonly DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(MyBackground), typeof(MyComponent), new FrameworkPropertyMetadata(default(MyBackground), new PropertyChangedCallback(OnPropertyChanged))); } MyBackground is a class that derives from DependencyObject and it has some DependencyProperties. public class MyBackground : DependencyObject { public Color BaseColor { set { SetValue(BaseColorProperty, value); } get { return (Color)GetValue(BaseColorProperty); } } public static readonly DependencyProperty BaseColorProperty = DependencyProperty.Register("BaseColor", typeof(Color), typeof(MyBackground ), new UIPropertyMetadata(Colors.White)); [...] } Now, what I want is when a property from MyBackground is changed, MyComponent to be notified that MyBackground has changed and the PropertyChangedCallback named OnPropertyChanged to be called.

    Read the article

  • ASP.NET MVC - ASPX with non-default constructor

    - by bh213
    Is it possible for a ASPX view (in ASP.NET MVC) to have non-default constructor AND use this constructor when creating this view? Example - Page will inherit from this class: public class ViewPageWithHelper<TModel> : System.Web.Mvc.ViewPage<TModel> where TModel : class { public ViewPageWithHelper(Helpers helpers) { Helpers = helpers; } protected Helpers Helpers { get; private set; } } ASPX view: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="MyInjectedViewPage<MyModel>" %> <% Helpers.XXXX %> Now, I'd like to inject Helpers into view somehow - automatically. Ideas?

    Read the article

  • Is there a pattern for initializing objects created wth a DI container

    - by Igor Zevaka
    I am trying to get Unity to manage the creation of my objects and I want to have some initialization parameters that are not known until run-time: At the moment the only way I could think of the way to do it is to have an Init method on the interface. interface IMyIntf { void Initialize(string runTimeParam); string RunTimeParam { get; } } Then to use it (in Unity) I would do this: var IMyIntf = unityContainer.Resolve<IMyIntf>(); IMyIntf.Initialize("somevalue"); In this scenario runTimeParam param is determined at run-time based on user input. The trivial case here simply returns the value of runTimeParam but in reality the parameter will be something like file name and initialize method will do something with the file. This creates a number of issues, namely that the Initialize method is available on the interface and can be called multiple times. Setting a flag in the implementation and throwing exception on repeated call to Initialize seems way clunky. At the point where I resolve my interface I don't want to know anything about the implementation of IMyIntf. What I do want, though, is the knowledge that this interface needs certain one time initialization parameters. Is there a way to somehow annotate(attributes?) the interface with this information and pass those to framework when the object is created? Edit: Described the interface a bit more.

    Read the article

  • How do I configure StructureMap to use a generic repository?

    - by simonjreid
    I have an interface IGenericRepository<TEntity> where TEntity : IEntity and an implementation GenericRepository<TEntity> where TEntity : Entity. I'm trying to inject a specific IGenericRepository<Section> into a class using StructureMap: ObjectFactory.Initialize(x => { x.For(typeof(IGenericRepository<>)).Use(typeof(GenericRepository<>)); }); But when I try to use ObjectFactory.GetInstance<IGenericRepository<Section>>(); I get: StructureMap Exception Code: 202 No Default Instance defined for PluginFamily System.Data.Common.DbConnection Any ideas why this is or what I'm doing wrong? Thanks in advance, Simon

    Read the article

  • 2 Classes need each other declared C++

    - by Prodigga
    I have a "Game" class which holds all the games settings and manages the game. I have a "Grid" class which is the grid the game is played on. The "Game" class initializes a "Grid" object as one of its members (passing itself ("this") as one of the parameters for "Grid"s constructor).. The "Grid" object therefor needs to deal with a "Game*" pointer. To do this it needs to know what "Game" is; i need to declare it before "Grid". But "Game" uses "Grid"...so it also needs "Grid" declared before it. so confused on how to include headers/etc correctly here..

    Read the article

< Previous Page | 26 27 28 29 30 31 32 33 34 35 36 37  | Next Page >