views:

185

answers:

1

I have a web user control which call some methods of an interface. Four different classes use this interface.

public interface IMultiTextProvider
{
    bool Insert(string text, Guid campaignId);
    IEnumerable<IMultiTextItem> GetItems(Guid campaignId);
}

In init or load I am setting up the controls like this (where wuc* is a control id, and Provider is property of a class which implements the interface):

    private void SetMulitTextClassTypes()
    {
        wucMultiTextHandsetOrPlan.Provider = new HandsetOrPlanProvider();
        wucMultiTextCallToAction.Provider = new CallToActionProvider();
        wucMultiTextBonuses.Provider = new BonusProvider();
        wucMultiTextRequirements.Provider = new RequirementProvider();
    }

The question is, can I do this declaratively in the control?
I am trying to use an object data source and the property is instantiated too late.

<CSControl:MultiTextUpdate ID="wucMultiTextBonuses" ControlTitle="Bonuses" runat="server" Provider="what goes here???" CampaignId="<%# CampaignId %>" />

And is there a much better model to use when writing one control to run functions in an interface? Maybe I need ProviderType instead of Provider and a way to invoke a new instance...?

+1  A: 

I would go for the "ProviderType" solution, using as a property of the control to get the type to instantiate. Here's a quick example on how to create an object starting from the type name (with a console application).

namespace TypeTest{

    public interface IMultiTextProvider {
        bool Insert(string text, Guid campaignId);
    }

    public class BonusProvider : IMultiTextProvider {
        public bool Insert(string text, Guid campaignId) {
            return true;
        }
    }

    class Program {
        static void Main(string[] args) {

            string typeName = "TypeTest.BonusProvider";
            Type providerType = Type.GetType(typeName);
            IMultiTextProvider provider = Activator.CreateInstance(providerType)
                as IMultiTextProvider;
            if (null == provider) {
                throw new ArgumentException("ProviderType does not implement IMultiTextProvider interface");
            }
            Console.WriteLine(provider.Insert("test",new Guid()));
        }
    }
}
Paolo Tedesco