1

Is this the best practice for injecting a class dependency into a repository? Bear in mind that other repositories will need this PetaPoco.Database instance as I want each repository to use a shared database connection object.

public class ConfigRepository : IConfigRepository
{
        private Database DB;

        public ConfigRepository(PetaPoco.Database db)
        {
            DB = db;
        }
}

//Here is how structuremap is configured

    ObjectFactory.Initialize(x =>
    {
        x.Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
            scan.AddAllTypesOf<IController>();


        });

        x.Register<PetaPoco.Database>(new PetaPoco.Database("DBConnection"));

        x.For<IConfigRepository>().Use<ConfigRepository>();

    });
    return ObjectFactory.Container;
Jon
  • 38,814
  • 81
  • 233
  • 382
  • it really depends what x is? There might be a better syntax for defining a singleton – Simon Halsey Sep 16 '11 at 11:13
  • Do you know how PetaPoco.Database should be managed? Is it a UnitOfWork? Singleton? – alexn Sep 16 '11 at 12:03
  • I dont I'm afraid. I was hoping to use the same instance object throughout the app as I know that is possible with PetaPoco – Jon Sep 16 '11 at 12:39

1 Answers1

1

I'm told this is what you need:

x.For<PetaPoco.Database>().Singleton().Use(()=>new PetaPoco.Database("connectionString"));
Simon Halsey
  • 5,459
  • 1
  • 21
  • 32
  • Who told you that? How is it different to my approach? – Jon Sep 16 '11 at 13:41
  • It ensures the database is used as a singleton. It was suggested by someone I work with who uses StructureMap. It would be backed up by this http://stackoverflow.com/questions/2363458/structuremap-singleton-usage-a-class-implementing-two-interface, this http://stackoverflow.com/questions/1600759/with-structuremap-is-it-possible-to-make-a-singleton-object-and-provide-construct and this http://abstractcode.com/abstractblog/archive/2010/06/13/structuremap-part-2-ndash-instance-lifecycles.aspx – Simon Halsey Sep 16 '11 at 14:51
  • In my code does that mean a new Database object is created every time then? – Jon Sep 16 '11 at 14:54
  • No, it's treated as a singleton. That means one & only one instance is created and used everytime. You need to be sure any methods are thread safe as a singleton will be used by all threads (only one instance see). – Simon Halsey Sep 16 '11 at 14:55
  • Well, I'm not sure, but I would have assumed they act very similar. Using the singleton approach may enforce scoping in a stronger manner. – Simon Halsey Sep 16 '11 at 15:01